将组合框中的 SelectedItem 与当前 ItemSsource 绑定?

Binding SelectedItem in comobox with current ItemSource?

所以我想要实现的是将 ItemsSource 中的当前项目绑定到 Comobox 中的 SelectedItem 我希望以下(一个简化的示例)代码能够演示我想要的。

public class book : INotifyPropertyChanged{
private string _title;
private string _author;

public book(){
    this.Title = "";
    this.
}
public string Title{
    get{return _title;}
    set{
        _title = value;
                NotifyPropertyChanged("Title");

    }
}
public string Author{
    get{return _author;}
    set{
        _author = value;
        NotifyPropertyChanged("Author");
    }
}

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

ThisViewModel.cs代码:

public class ThisViewModel{
    private ObservableCollection<Book> _book;
    private List<Book> _existedBooks;
    public ObservableCollection<Book> Book{
        get{return _book;}
        set{_book = value;}
    }

    public ThisViewModel(){
        Books = new ObservableCollection<Book>();
        Books.Add(new Book())
    }
    public List<Book> ExistedBooks{
        get{return _existedBooks;}
        set{_existedBooks = value;}
    }
}

ThisView.xaml.cs 的代码隐藏:

public partial class ThisView{
    public ThisView(){
        InitializeComponent();
        this.DataContext = new ThisViewModel();

    }
}

XAML代码ThisView.xaml:

<ItemsControl ItemsSource="{Binding Path=Book}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ComboBox  ItemsSource="{Binding Path=ExistedBooks}"  
            DisplayMemberPath="Title"
            SelectedItem="{Binding <HERE IS MY PROBLEM>}"
            ></ComboBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如何将 selectedItem(existedBooks 之一)绑定到 ItemsControl 当前项目(书籍)。

希望我的观点足够清楚。 谢谢你的时间。

您应该将相同的 Book 对象添加到两个集合中才能正常工作:

public ThisViewModel()
{
    Book = new ObservableCollection<Book>();
    ExistedBooks = new List<Book>();

    Book bookA = new Book() { Title = "Title A" };
    Book.Add(bookA);
    ExistedBooks.Add(bookA);
}

然后你可以像这样将 ComboBox 的 SelectedItem 属性 绑定到 ItemsControl 中的当前项目:

<ItemsControl ItemsSource="{Binding Path=Book}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ComboBox  ItemsSource="{Binding DataContext.ExistedBooks, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                               SelectedItem="{Binding Path=., Mode=OneWay}"
                               DisplayMemberPath="Title" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>