且构网

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

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

更新时间:2022-05-03 02:42:58

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.

此外,您的VM并不完全遵循***实践.您使用的是List<T>而不是ObservableCollection<T>,并且将其公开为List<T>,而不是像ICollection<T>这样的简单名称.

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>.