[英]How to set a default value which is bound to another value for the combobox in datagrid
[英]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.