Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a datatemplate for grid panel elements in WPF?

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 the grid location. I really like how I can create data templates in the listbox XAML to create a UI with almost nothing in the code behind for it. Is there a way to create a data template for grid panel elements, and bind the panel to a data collection?

like image 921
tbischel Avatar asked Jul 14 '10 22:07

tbischel


1 Answers

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"}
        };
    }
like image 51
Heinzi Avatar answered Nov 08 '22 19:11

Heinzi