我有一个简单的类TestClass
,它包含一个属性字符串Rep
并实现INotifyPropertyChanged
接口:
public class TestClass : INotifyPropertyChanged
{
private String rep;
public String Rep
{
get { return rep; }
set { rep = value; OnPropertyChanged(); }
}
public TestClass(String name)
{
Rep = name;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我的Window
有一个ListBox
,ComboBox
作为DataTemplate。
在我的Window
课程中,我创建了两个ObservableCollections<TestClass>
。一个应该是列表中ItemsSource
es的ComboBox
,另一个应该是用户通过ComboBox
es选择的项目存储的位置。
Items
中的项目是对ComboSource
中项目的引用非常重要。
public partial class MainWindow : Window
{
private ObservableCollection<TestClass> items;
private ObservableCollection<TestClass> comboSource;
public MainWindow()
{
InitializeComponent();
DataContext = this;
ComboSource = new ObservableCollection<TestClass>();
ComboSource.Add(new TestClass("4"));
ComboSource.Add(new TestClass("5"));
ComboSource.Add(new TestClass("6"));
Items = new ObservableCollection<TestClass>();
Items.Add(ComboSource[0]);
Items.Add(ComboSource[1]);
Items.Add(ComboSource[2]);
}
public ObservableCollection<TestClass> Items
{
get { return items; }
set { items = value; }
}
public ObservableCollection<TestClass> ComboSource
{
get { return comboSource; }
set { comboSource = value; }
}
}
XAML:
<Grid>
<StackPanel>
<ListBox ItemsSource="{Binding Items}" Height="200">
<ListBox.ItemTemplate>
<DataTemplate>
<ComboBox Width="50"
SelectedItem="{Binding Path=., Mode=TwoWay}"
ItemsSource="{Binding ComboSource,
RelativeSource={RelativeSource AncestorType=Window}}"
DisplayMemberPath="Rep"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
我正在使用三个ComboSource
对象初始化TestClass
,然后将这些对象也放在Items
中。
我想要的是当用户选择例如在列表中第二个5
中具有Rep ComboBox
的项目,它应该替换&#34;项目&#34;中第二个位置的引用。同样。
出于某种原因,启动SelectedItem
绑定似乎工作正常,但是当我在ComboBox
中选择其他项时,它不会更新Items
列表。< / p>
编辑:
这是一张图片,应该澄清我想要实现的目标。我对引用的意思是,我不希望Items
包含两个不同的5
个对象,而只需要两个引用 ComboSource
中的对象。