[英]Set WPF DataGrid ComboBoxColumn ItemSource with Binding - MVVM
[英]WPF MVVM DataGrid ComboboxColumn binding to List in my Model
我目前正在使用MVVM進行WPF項目。
我有一個綁定到這樣的模型的ObservableCollection
的DataGrid
:
class Model : INotifyPropertyChanged
{
private string m_Name;
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value;
OnPropertyChanged("Name");
}
}
private List<string> m_Names;
public List<string> Names
{
get
{
return m_Names;
}
set
{
m_Names = value;
OnPropertyChanged("Names");
}
}
private double? m_Value;
public double? Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
OnPropertyChanged("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
現在,我想使用DataGridComboBoxColumn
來創建一個組合框,其屬性“名稱”為SelectedItem,名稱為ItemSource。
我的每個模型都有自己的一組名稱,這些名稱與其他任何模型的名稱都不相同。
我已經迷糊了,並通過StackOverflow查看,但是我沒有找到任何解決方案。 我也曾嘗試過過濾器,就像我知道DevExpress Grid Controls可以做到的那樣,但是我沒有找到基本的WPF DataGrid的任何東西。
如何將DataGridComboBoxColumn
綁定到模型中的屬性List
?
如果使用DataGridComboBoxColumn,則必須使用靜態資源來填充ItemsSource,這在“備注”部分中進行了說明:https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.controls.datagridcomboboxcolumn?view = netframework-4.8
因為每個視圖模型都有不同的“名稱”,所以可以使用DataGridTemplateColumn代替DataGridComboBoxColumn
<DataGridTemplateColumn Header="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
你嘗試了什么? 假設DataGrid
的ItemsSource
屬性已設置或綁定到IEnumerable<Model>
,則此方法應該起作用:
<DataGridComboBoxColumn ItemsSource="{Binding Names}" SelectedItemBinding="{Binding Name}" />
請參考這篇 TechNet文章以獲取更多建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.