且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 WPF DataGridComboBoxColumn 与 MVVM 结合使用 - 绑定到 ViewModel 中的属性

更新时间:2022-01-23 02:29:39

DataGrid 列定义没有以您期望的方式参与逻辑树.这很荒谬,但最后我检查过你必须做这样的事情:

DataGrid column definitions don't participate in the logical tree in the way you would expect. It's ridiculous, but last I checked you have to do something like this:

<DataGridComboBoxColumn Header="CourtType" SelectedItemBinding="{Binding Type}">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.CourtCodesTypeCourt}"/>
            <Setter Property="IsReadOnly" Value="True"/>
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.CourtCodesTypeCourt}"/>
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

您会注意到我还将您的 TextBinding 更改为 SelectedItemBinding.我不确定您是否真的想要 TextBinding,但如果您只想允许用户在列表之间进行选择,那么 SelectedItemBinding 可能就是您想要的.

You'll notice I've also changed your TextBinding to a SelectedItemBinding. I'm not sure if you actually intended a TextBinding, but if you just want to allow the user to select between the list, then SelectedItemBinding is likely what you want.

此外,您的虚拟机并没有完全遵循***实践.您正在使用 List 而不是 ObservableCollection,并且您将其公开为 List 而不是某些东西更简单的比如ICollection.

Also, your VMs don't exactly follow best practices. You're using List<T> instead of ObservableCollection<T>, and you're exposing it as List<T> rather than something simpler such as ICollection<T>.