c# - ComboBox SelectedItem 绑定
问题描述
我的视图中有一个组合框:
<ComboBox Name="comboBox1" ItemsSource="{Binding MandantList}" SelectedItem="{Binding CurrentMandant, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Firma}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
这是我的模型:
public class MandantListItem : INotifyPropertyChanged
{
public MandantListItem() { }
string _Firma;
bool _IsChecked;
public string Firma
{
get { return _Firma; }
set { _Firma = value; }
}
public bool IsChecked
{
get
{
return _IsChecked;
}
set
{
_IsChecked = value;
OnPropertyChanged(nameof(IsChecked));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这是我的ViewModel:
public class MaViewModel : INotifyPropertyChanged
{
public ObservableCollection<MandantListItem> MandantList { get { return _MandantList; } }
public ObservableCollection<MandantListItem> _MandantList = new ObservableCollection<MandantListItem>();
private MandantListItem _CurrentMandant;
public MandantListItem CurrentMandant
{
get { return _CurrentMandant; }
set
{
if (value != _CurrentMandant)
{
_CurrentMandant = value;
OnPropertyChanged("CurrentMandant");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
如何填充组合框:
public zTiredV2.ViewModel.MaViewModel MAList = new zTiredV2.ViewModel.MaViewModel();
this.comboBox1.ItemsSource = MAList.MandantList;
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "A", Homepage = "a.com", IsChecked = false });
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "B", Homepage = "b.com", IsChecked = false });
但是我的项目没有更新......也通过 IsChecked 尝试过,但也没有成功......当我遍历 MAList 时,IsChecked 总是错误的。以及如何将 TextBlock 绑定到选定的 Firma?
MVVM 很难,但我喜欢它。
解决方案
您应该将 的 设置DataContext
为ComboBox
您的视图模型的实例。否则绑定将不起作用:
this.comboBox1.DataContext = MAList;
另请注意,_MandantList
您的财产的支持字段不应公开。事实上,你根本不需要它:
public ObservableCollection<MandantListItem> MandantList { get; } = new ObservableCollection<MandantListItem>();
当DataContext
您CurrentMandant
在ComboBox
. 它不会设置IsChecked
属性。
推荐阅读
- hana - HANA Studio:具有多个 IF 语句的计算列
- android - 如何在手动设置所有设置(包括闪光灯)的情况下拍摄照片,而不会丢失包含完整闪光灯的图像?
- java - 模拟链式休息客户端调用(Mockito)
- android - 什么时候会单独使用 findNavController 方法而不是 NavHostFragment?
- angular - 如何在角度/离子的路线中写入条件
- c# - 使用身份框架进行用户身份验证的现有应用程序的 Azure Active Directory 身份验证。使用 ADAL 或 Web API
- javascript - UI 没有被 fetch 的结果更新
- javascript - 如何在 Plotly Dash 中注册鼠标单击和拖动事件?
- javascript - ReactQuill(富文本) - 错误:React.Children.only 期望接收单个 React 元素子 - React
- ios - 滚动表格视图时如何获取节号