繁体   English   中英

DataGrid中的ComboBox:ItemSource绑定到动态资源,如何设置默认行?

[英]ComboBox in DataGrid: ItemSource bound to dynamic resource, how to set default row?

我正在[用于学校]的C#项目中使用WPF并实现MVP。 在这段代码中,我得到了一个显示潜水员列表的DataGrid。 第一列是“名称”,第二列应显示“ DivingType”。 DivingType是一个内置对象,它具有属性ID,例如103A。 其中大约有400个存储在一个列表中,每个Diver(“行”)都有一个Dives( List<Dive> )属性,而每个Dives都有一个DivingType属性。

我们要拥有的是,此列默认情况下将显示与潜水者相关联的DivingType.ID,但是下拉列表应包含所有潜水类型,这样您就可以从那里进行更改[并更新潜水者宾语]。 更复杂的是,这是我们作为UserControls添加到窗口中的众多视图之一。

话虽如此,这里是代码。 我试图消除不必要的混乱,我确信这对结果没有影响。

<Window ...>
    <Window.Resources>
        <local:Presenter x:Key="myPresenter"/>
    </Window.Resources>
    <DockPanel DataContext="{StaticResource myPresenter}">
        <UserControl ...>
            <DataGrid ItemsSource="{Binding DiverList}" x:Name="datagrid">
                    <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Width="1*" Binding="{Binding Name}"/>
                    <DataGridTemplateColumn Header="Diving type" Width="1*">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, 
                                                                Path=DataContext.DivingTypes}"
                                          DisplayMemberPath="ID"
                                          SelectedValue="{Binding Dives[0]}"
                                          SelectedValuePath="divingType">
                                </ComboBox>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </UserControl>
   </DockPanel>
</Window>

程序运行时,我在组合框中获得了所有DivingTypes.ID,但没有选定的值。 该代码不会在输出窗口中放入任何相关错误。 我相信会发生什么事,它调用了DivingType.Equals,但传递了行(Diver)而不是我指定的SelectedValuePath的DataContext。 有什么方法可以覆盖XAML中的此行为? 还是有更简单的方法来实现这一目标?

编辑:从那以后,我已经编辑了上面发布的代码为:

<ComboBox ItemsSource="{
                           Binding RelativeSource={
                               RelativeSource AncestorType=UserControl
                           }, 
                           Path=DataContext.DivingTypes
                       }"
          SelectedValue="{
                            Binding Dives[0].divingType, Mode=TwoWay
                         }"
/>

这将使正确的值在开始时显示在组合框中,从Diver.Dives [0] .divingType加载DivingType.ID,但是当我在下拉框中选择新值时,它仍然没有设置属性。

使用UpdateSourceTrigger = PropertyChanged。

在这里解释。

您是否尝试过在视图模型中实现INotifyPropertyChanged,然后在设置SelectedValue时引发PropertyChanged事件。

如果这不起作用,可以设置SelectedValue吗?

SelectedValue="{Binding Path=divingType, Mode=TwoWay}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM