is there a datatemplate for grid panel elements in WPF?

前端 未结 2 1332
抹茶落季
抹茶落季 2020-12-29 15:45

Fairly new to WPF...

I have a collection of data I would like to bind to a grid panel. Each object contains its grid row and column, as well as stuff to fill in at

相关标签:
2条回答
  • 2020-12-29 16:24

    You can use an ItemsControl with a Grid as its panel. Here is an example. 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>
    

    Codebehind (for testing purposes):

        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"}
            };
        }
    
    0 讨论(0)
  • 2020-12-29 16:38

    Not sure if this will help you, but why don't you try setting the ItemsPanel of an ItemsControl (ListBox, ListView) to a UniformGrid. Something like this:

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

    It's similar to the previous solution, only a little more dynamic.

    0 讨论(0)
提交回复
热议问题