【问题标题】:WPF creating multiple groups of controlsWPF 创建多组控件
【发布时间】:2015-07-19 17:36:58
【问题描述】:

假设我有五个文本框和它们旁边的五个复选框。

现在我想创建 x 组这样的控件,然后将它与一个对象列表绑定,该列表将包含来自文本框的文本和有关复选框是否被选中的数据。

这样的常见方法是什么?

我开始编写一个函数,该函数将循环 x 次,在现有 Grid 中创建新的 RowDefinition,然后在该 Row 中创建另一个 Grid,在该 Grid 中创建五行和两列,并添加所有这些控件,设置它们的行,列,添加绑定等,但我认为这不是正确的方法,写所有这些太麻烦了。一定有更好的办法。

【问题讨论】:

  • 试试 DataTemplate 和 ItemsControl。

标签: c# wpf binding controls


【解决方案1】:

您可以使用 ItemsControl 和为项目定义数据模板来实现此功能。请参考以下代码。我以 3 个文本框和复选框为例。

<StackPanel>
    <ItemsControl x:Name="itms">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBox Width="50" Text="{Binding Text1}" Grid.Row="0" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check1}" Content="Check1" Grid.Row="0" Grid.Column="1"/>
                    <TextBox Width="50" Text="{Binding Text2}" Grid.Row="1" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check2}" Content="Check2" Grid.Row="1" Grid.Column="1"/>
                    <TextBox Width="50" Text="{Binding Text3}" Grid.Row="2" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check3}" Content="Check3" Grid.Row="2" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    <Button Click="Button_Click" Content="Add Items"></Button>
</StackPanel>

public partial class Window2 : Window
{
    ObservableCollection<MyClass> lst = new ObservableCollection<MyClass>();
    public Window2()
    {
        InitializeComponent();
        itms.ItemsSource = lst;

    }
    int i = 0;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        i++;
        lst.Add(new MyClass() { Text1 = i.ToString(), Text2 =i.ToString()+1,Text3=i.ToString()+2,Check1=true,Check2=true,Check3=false});
    }
}

class MyClass
{
    public string Text1 { get; set; }
    public string Text2 { get; set; }
    public string Text3 { get; set; }
    public bool Check1 { get; set; }
    public bool Check2 { get; set; }
    public bool Check3 { get; set; }
}

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2012-05-25
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2013-09-16
    • 1970-01-01
    相关资源
    最近更新 更多