【问题标题】:is there a datatemplate for grid panel elements in WPF?WPF 中有网格面板元素的数据模板吗?
【发布时间】:2014-10-19 06:20:11
【问题描述】:

对 WPF 相当陌生...

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

【问题讨论】:

    标签: c# wpf grid datatemplate


    【解决方案1】:

    您可以使用ItemsControlGrid 作为其面板。这是一个例子。 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"}
            };
        }
    

    【讨论】:

    • 如果您有已知的要显示的行数,这会很好地工作,但它不允许您根据数据的数量显示任意数量的行。
    • 我试图从 DataTemplate 设置行和列(在模板中的根元素上)并且想知道为什么它不起作用。这帮助很大。谢谢!
    【解决方案2】:

    不确定这是否对您有所帮助,但您为什么不尝试将 ItemsControl(ListBox、ListView)的 ItemsPanel 设置为 UniformGrid。像这样的:

    <ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    它与之前的解决方案类似,只是动态化了一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多