所以我想要实现的是将当前项目从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(其中一个已存在的Book)绑定到ItemsControl当前的Item(Book)。
希望我明白我的观点。 谢谢你的时间。
答案 0 :(得分:0)
您应该将相同的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>