c# - WPF 中是否有用于网格面板元素的数据模板?

标签 c# wpf grid datatemplate

对 WPF 相当陌生......

我有一组数据要绑定(bind)到网格面板。每个对象都包含其网格行和列,以及要在网格位置填充的内容。我真的很喜欢我如何在列表框 XAML 中创建数据模板来创建一个 UI,而其背后的代码几乎没有任何内容。有没有办法为网格面板元素创建数据模板,并将面板绑定(bind)到数据集合?

最佳答案

您可以使用带有 GridItemsControl 作为其面板。这是一个例子。 XAML:

    <ItemsControl x:Name="myItems">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding MyText}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Style.Setters>
                    <Setter Property="Grid.Row" Value="{Binding MyRow}" />
                    <Setter Property="Grid.Column" Value="{Binding MyColumn}" />
                </Style.Setters>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>

代码隐藏(用于测试目的):

    public Window1()
    {
        InitializeComponent();
        myItems.ItemsSource = new[] {
            new {MyRow = 0, MyColumn = 0, MyText="top left"},
            new {MyRow = 1, MyColumn = 1, MyText="middle"},
            new {MyRow = 2, MyColumn = 2, MyText="bottom right"}
        };
    }

关于c# - WPF 中是否有用于网格面板元素的数据模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3251081/

相关文章:

c# - Xamarin ContentView/View 生命周期

c# - 在 C# 中读取视频元数据

c# - 无法初始化集合但 nhibernate 生成正确的 sql 并在 sql server 中无错误地执行

c# - 如何将WPF英寸单位转换为Winforms像素,反之亦然?

WPF PRISM - 在不解析实例的情况下向区域注册 View

grid - Telerik MVC Grid Control 带有 ActionLink 的附加列

c# - 改进属性(property)监控代码?

wpf - WPF 中 ToggleButton 的 IsChecked 属性的 OneWay 绑定(bind)

wpf - 如何将网格的子项绑定(bind)到列表?

css - 带有流体槽的固定宽度列