使用mvvm在WPF DataGrid中绑定级联组合框项源 [英] Binding cascading combobox itemsource in wpf datagrid using mvvm

查看:88
本文介绍了使用mvvm在WPF DataGrid中绑定级联组合框项源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用mvvm根据第一个下拉列表的第一个下拉列表选择值绑定第二个下拉列表

How to bind a 2nd dropdown based on first dropdown selected value of first dropdown using mvvm

这是类结构

List<Location> Locations; //Application global cached data 
List<Room> Room; //Application global cached data 
class Location {LocationId, Name ....} 
class Room{RoomId, Name, LocationId...}

XAML

 <DataGridTemplateColumn Header="Property Name">
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox Name="LocationsComboBox"
                  ItemsSource="{Binding Path=DataContext.Locations, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"                
                  DisplayMemberPath="Name" SelectedValuePath="Id"
                  SelectedValue="{Binding PropertyId, UpdateSourceTrigger=PropertyChanged}">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--Room Number-->
<DataGridTemplateColumn Header="Room Number">
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox Name="RoomComboBox"
                  ItemsSource="{Binding Path=DataContext.Rooms, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"               
                  DisplayMemberPath="RoomName" SelectedValuePath="RoomId"
                  SelectedValue="{Binding NewRoomId, UpdateSourceTrigger=PropertyChanged}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <i:InvokeCommandAction 
                            Command="{Binding DataContext.PropertyChangedCommand, 
                                    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" 
                            CommandParameter="{Binding}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>


推荐答案

使用ObservableCollection< Room>

Use ObservableCollection<Room> instead of List (this will cause the second combobox to update when the first combo box changes the location which in turn causes the room collection to change.

使用ObservableCollection< Location> ;,而不是列表(这将导致第二个组合框在第一个组合框更改位置时更新,从而又导致房间集合发生更改。)您的位置可能永远都不会改变,但这只是很好的MVVM形式。

Use ObservableCollection<Location> also. Your locations might not ever change, but this is simply good MVVM form.

这篇关于使用mvvm在WPF DataGrid中绑定级联组合框项源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆