【发布时间】:2018-04-24 21:49:10
【问题描述】:
我是 WPF 中的 MVVM 新手,遇到以下问题。
我尝试拥有的是两个 ComboBox,每个都绑定到与 ItemsSource 相同的 ObservableCollection<TwoProperties> DList 属性并与 SelectedItem 同步,所以我在我的 XAML 中写了这个
<ComboBox ItemsSource="{Binding DList}" DisplayMemberPath="Property1" SelectedItem="{Binding SelectedD}" />
<ComboBox ItemsSource="{Binding DList}" DisplayMemberPath="Property2" SelectedItem="{Binding SelectedD}" />
使用此视图模型
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<TwoProperties> _dList =
new ObservableCollection<TwoProperties> {
new TwoProperties(1,"one"),
new TwoProperties(2,"two")
};
public ObservableCollection<TwoProperties> DList
{
get { return _dList; }
set { _dList = value; OnPropertyChanged("DList"); }
}
private TwoProperties _selectedD;
public TwoProperties SelectedD
{
get { return _selectedD; }
set { _selectedD = value; OnPropertyChanged("SelectedD"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
在哪里
public class TwoProperties
{
public double Property1 { get; set; }
public string Property2 { get; set; }
public TwoProperties (double p1, string p2)
{
Property1 = p1;
Property2 = p2;
}
}
我还希望有两个文本框来显示同步组合框的当前SelectedItem 的属性。 SelectedD 的属性 Property1 和 Property2 应该是可编辑,但是 ObservableCollection<TwoProperties> _dList 应该保持不变/只读,并且不会更改其值。
<TextBox Text="{Binding SelectedD.Property1}" />
<TextBox Text="{Binding SelectedD.Property2}" />
但是当我编辑 TextBoxes 并因此编辑 SelectedD 时,_dList 也会更改其值,这不是我想要的。
我希望我能解释我的问题。我确定我在这里遗漏了一些简单的东西。
【问题讨论】:
标签: c# wpf mvvm data-binding combobox