[英]How would I add Checbox dynamically into a Grid in WPF application
當我在C#Desktop應用程序中加載窗口時,我想動態地在Grid
控件中添加一些Checkbox
。 復選框出現的次數取決於表中的條目數。 在這里,我使用了LINQ To SQL
類。 網格控件在XAML中定義。
...
<Grid Name="grid1">
<!-- here i would like to show all check box -->
</Grid>
...
代碼隱藏文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
// class declaration ...
...
private void course_Loaded(object sender, RoutedEventArgs e)
{
List<Course> courses = ldc.Courses.ToList();
foreach (var c in courses)
{
CheckBox cb = new CheckBox();
cb.Name=c.CourseID.ToString();
cb.Content = c.CourseID.ToString();
//grid1.Controls.Add(cb); does not work. what to do here?
}
}
此代碼無效。 任何建議? 謝謝。
你這樣做是錯的。
首先要說你可以做grid1.Children.Add(cb);
那么真正的問題是你正在使用網格來顯示列表。 在WPF中有一個非常好的ListView,具有完全可樣式化的行,可以包含復選框和幾乎所有你能想象到的東西。
我不知道你的數據是什么樣的,所以我無法在ListView上擴展太多,但是類似的東西
<ListView ItemsSource="{Binding Courses}">
<ListView.View>
<GridView>
<GridViewColumn Width="120">
<GridViewColumnHeader>
<TextBlock Text="Course Name"/>
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ...UFigureThisOut}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="120">
<GridViewColumnHeader>
<TextBlock Text="Take That"/>
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding ...UFigureThisOutToo}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
我建議將這些CheckBox添加到StackPanel,然后將StackPanel添加到網格中:
StackPanel innerStack;
private void course_Loaded(object sender, RoutedEventArgs e)
{
innerStack= new StackPanel
{
Orientation=Orientation.Vertical
};
List<Course> courses = ldc.Courses.ToList();
foreach (var c in courses)
{
CheckBox cb = new CheckBox();
cb.Name = c.CourseID.ToString();
cb.Content = c.CourseID.ToString();
innerStack.Children.Add(cb);
}
Grid.SetColumn(innerStack, /*Set the column of your stackPanel, default is 0*/);
Grid.SetRow(innerStack, /*Set the row of your stackPanel, default is 0*/);
Grid.SetColumnSpan(innerStack, /*Set the columnSpan of your stackPanel, default is 1*/);
Grid.SetRowSpan(innerStack, /*Set the rowSpan of your stackPanel, default is 1*/);
Grid.Children.Add(innerStack);
}
如果您不需要此結構,則應向網格添加一些RowDefinition並使用Grid.SetRow(cb,int)方法將ComboBox彼此放在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.