ListBox中的ComboBox的SelectedItem绑定不工作TwoWay

时间:2017-05-24 13:37:12

标签: c# wpf xaml combobox listbox

我有一个简单的类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有一个ListBoxComboBox作为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>

enter image description here

编辑: 这是一张图片,应该澄清我想要实现的目标。我对引用的意思是,我不希望Items包含两个不同的5个对象,而只需要两个引用 ComboSource中的对象。

enter image description here

0 个答案:

没有答案