集合中嵌套对象到自定义DataGridCell模板的WPF动态DataGrid绑定值



我花了半天多的时间来整理这个任务,对于一棵树,我看不到森林。

目的是将数据(DataGrid)显示为具有动态列计数的多个网格,其中每个单元格(而不仅仅是列)可以或不能通过双向绑定进行编辑

我想避免使用代码隐藏的方法,我相信xaml可以为我提供我需要的东西。另一件事是mvvm注入。

让我们简单一点,先对一张表进行绑定。

我的第一个难题是创建DataTable,但这不能用于单元格可编辑级别。然后我创建了对象集合的集合(对于一个表->多行->多列)。

public class DataGridCell : BaseViewModel
{     
    public string Value
     ....
    public bool IsEditable
     ....     
}

然后我有另一个VM,它代表一个表(网格),其中包含上的VM

public class DataGridItem : BaseViewModel
{    
    public string TableName
    {
     ....
    }
    public ObservableCollection<ObservableCollection<DataGridCell>> Data
    {
     ....
    }
}

然后我的xaml看起来像这个

<DataGrid ItemsSource="{Binding Path=Data}" AutoGenerateColumns="True">
    <DataGrid.Resources>
        <DataTemplate x:Key="ReadonlyCellTemplate">
            <TextBlock Text="{Binding Value}" />
        </DataTemplate>
        <DataTemplate x:Key="EditableCellTemplate">
            <TextBox Text="{Binding Value}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGridTemplateColumn CellTemplate="{StaticResource ReadonlyCellTemplate}">
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <ContentPresenter x:Name="Presenter" ContentTemplate="{StaticResource ReadonlyCellTemplate}" />
                <DataTemplate.Triggers>                             
                    <DataTrigger Binding="{Binding IsEditable, PresentationTraceSources.TraceLevel=High}" Value="True">
                        <Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource EditableCellTemplate}" />
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>
</DataGrid>

其思想是动态选择数据输入控件将填充哪个单元格,而不填充哪个单元格。问题是绑定。我不知道如何绑定集合中的具体单元元素

感谢任何可能的建议

我希望现在还不算太晚,但这就是我如何解决将细胞绑定到动态数据的问题:

XAML 中绑定到WPF DataGridCell内容的问题

(根据要求添加代码)

最新更新