[英]WPF Combobox binding selected item
我有以下問題。 我有這個模型:
public class A
{
public A(string id)
{
ID = id;
}
public string ID { get; }
public string Name { get ; set; }
public B objectB { get; set; }
}
public class B
{
public B(string id)
{
ID = id;
}
public string ID { get; }
public string Name { get; set; }
}
public class ViewModel
{
public ObservableCollection<A> ListOne = new ObservableCollection<A>();
public ObservableCollection<B> ListTwo = new ObservableCollection<B>();
public ViewModel()
{
B objectB = new B("1");
objectB.Name = "ObjectB";
B listElement2 = new B("2");
listElement2.Name = "ListElement2";
ListTwo.Add(objectB);
ListTwo.Add(listElement2);
A objectA = new A("A1");
objectA.Name = "objectA1";
objectA.objectB = objectB;
ListOne.Add(objectA);
}
}
<ListBox ItemsSource="{Binding ListOne}" Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<ComboBox ItemsSource="{Binding ElementName=MyListBox, Path=DataContext.ListTwo}"
DisplayMemberPath="Name"
SelectedItem="{Binding objectB}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Class A
包含一個 object ob Class B
。 我的ViewModel
包含兩個列表。 class A 對象的一個列表 (ListOne) 和第二個列表 (ListTwo) 包含 class B 的對象。
現在我想將listTwo
綁定到嵌入到listbox
中的combobox
。 listbox
顯示視圖listOne
中的所有對象。 如果我更改combobox
的選擇,我想更新列表框所選項目的屬性 objectB。 我還希望combobox
select 在初始化期間 objectB 的值。
請注意:我簡化了 model 和視圖模型以專注於問題。 NotifyProperties 等工作。 我對 combobox 的綁定感興趣。
我不知道這樣做。 我希望你能幫助我。
您可以執行以下操作:
<ComboBox
ItemsSource="{Binding ListB}"
SelectedItem="{Binding SelectedB}"
DisplayMemberPath="Name" Width="100"
/>
此外,您可以在 ViewModel 中添加以下代碼:
private ObservableCollection<B> listB = new ObservableCollection<B>();
public ObservableCollection<B> ListB
{
get { return this.listB; }
set { this.listB = value; NotifyPropertyChanged("ListB"); }
}
private B selectedB;
public B SelectedB
{
get { return this.selectedB; }
set { this.selectedB = value; NotifyPropertyChanged("SelectedB"); }
}
ViewModel()
{
//Fill your ListB with all possible values
this.SelectedB=ListB.FirstOrDefault(x=>x.ID==A.ObjectB.ID)
}
那么你的類可能是 INotifyPropertyChanged:
public class A : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public long ID=-1;
private string name = "";
public string Name
{
get { return this.name; }
set
{
this.name = value;
this.NotifyPropertyChanged("Name");
}
}
private B objectB;
public B ObjectB
{
get{return this.objectB;}
set
{
this.objectB=value;
this.NotifyPropertyChanged("B");
}
}
}
我幾乎可以肯定您也可以將 SelectedB 替換為 A.ObjectB 進行綁定,但需要進行一些測試來檢查它。 優點(或不方便取決於)是,如果您在 A.ObjectB 上綁定,則更改將在您更改 ComboBox 中的選定項目后立即生效。 這樣您就可以更改您的 ComboBox 值,而無需直接修改您的 A object,然后在關閉 Window 時,您可以要求保存或不保存,如果是,只需執行 A.ObjectB.ObjectB.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.