Wpf在Grid中绘制对象集合

时间:2017-05-10 07:32:02

标签: c# wpf mvvm grid itemscontrol

在我的wpf应用程序中,我想创建填充数据的网格视图。该集合是Observable对象集合

public class BindableProfileData : BindableBase
{

    private ProfileItem _profileModel;
    private BindableDPDataItem _dataModel;

    private int row;
    public int column;
    private int rowSpan;
    private int columnSpan;
    public int Row

    {
        get { return row; }
        set { SetProperty(ref row, value); }
    }

    public int Column
    {
        get { return column; }
        set { SetProperty(ref column, value); }
    }

    public int RowSpan
    {
        get { return rowSpan; }
        set { SetProperty(ref rowSpan, value); }
    }

    public int ColumnSpan
    {
        get { return columnSpan; }
        set { SetProperty(ref columnSpan, value); }
    }



    public string Name
    {
        get
        {
            return "STRING";
        }
    }
}

这是测试对象,但它已经包含有关哪些行和列控件应该出现以及columnSpan和rowSpac应该采用多少的信息。更多的是每个对象应该选择dataTemplate来使用ObservableCollection元素的绑定上下文来绘制自己。

因此实际上ObservableCollection将包含从BindableProfileData扩展的对象。

TextBoxCotainer : BindableProfileData {}
RangeBarContainer : BindableProfileData {}

到目前为止,我还没有写过这些模板,但我找到了一些东西。 this

要清除我希望能够绘制类似this

的内容

现在我尝试使用这种方法: `

<ItemsControl ItemsSource="{Binding SelectedCategory}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid helper:GridHelpers.RowCount="100"
                          helper:GridHelpers.ColumnCount="3"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Column}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

`

但是所有元素都在视图上的相同位置绘制:image

你能告诉我我做错了什么,或者有更好的办法来解决这个问题。任何建议都会有所帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

像这样声明ItemContainerStyle

<ItemsControl ItemsSource="{Binding SelectedCategory}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid helper:GridHelpers.RowCount="100"
                  helper:GridHelpers.ColumnCount="3"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Column}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Grid.Column" Value="{Binding Column}"/>
            <Setter Property="Grid.ColumnSpan" Value="{Binding ColumnSpan}"/>
            <Setter Property="Grid.Row" Value="{Binding Row}"/>
            <Setter Property="Grid.RowSpan" Value="{Binding RowSpan}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>