WPF MVVM table layout from data binding

2019-03-04 03:36发布

Lets suppose that I have the following models:

public class PageModel  //INotifyPropertyChanged...
{
    public int RowCount { get; set; }
    public int ColumnCount { get; set; }
    public ObservableCollection<BaseItemModel> PageItems { get; set; }
}

public abstract class BaseItemModel  //INotifyPropertyChanged...
{
    public string Name { get; set; }
    public int Row { get; set; }
    public int Column { get; set; }
}

public class ConcreteItem1 : BaseItemModel
{
    public bool Value { get; set; }
}

public class ConcreteItem2 : BaseItemModel
{
    public float Value { get; set; }
}

What I would like to do in WPF (without doing too much in the code-behind) is lay out the controls for the ConcreteItem1 and ConcreteItem2 in a table/grid format. The problem is I don't know how to approach this from a data binding standpoint.

It seems to me that UniformGrid would be the control of choice, but somehow embedding that as the layout for an items control?

What I'm aiming for is something like this:

enter image description here

Where the Rows/Columns is fixed and the controls scale to fill the available space.

So, how can I lay out controls data bound to a model in a table/grid format with fixed rows/columns?

标签: c# wpf mvvm
1条回答
smile是对你的礼貌
2楼-- · 2019-03-04 04:10

Set the ItemsPanel property to an ItemsPanelTemplate with a UniformGrid that specifies the number of columns:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

The number of rows are dependant on the number of items in the ItemsSource.

查看更多
登录 后发表回答