[英]Binding one listbox listboxitem from another listbox
我對C#WPF還是很陌生,所以請忍受我的問題。 我有兩個列表框(listbox1和listbox2),其中listbox1中的項目將在運行時通過用戶輸入添加或刪除。 我希望listbox2通過綁定方法相應地顯示其listboxitem。
例如,如果listbox1最初有5個項目,我希望listbox2顯示相同的5個項目。 如果在運行時添加或刪除listbox1中的項目,我希望listbox2顯示與listbox1相同的數據(項目)。
有人可以給我小費嗎? 提前致謝。
我對您的情況了解甚少,但可以說您擁有以下數據模型來保存您的數據,實現了INotifyPropertyChangedInterface:
public class A : INotifyPropertyChanged
{
public String SomeProperty {....}
...
}
然后,您將獲得一個包含您的項目的viewmodel,讓它繼承自som baseclass。 我推薦Galasoft MVVM Light,並進一步擴展您的需求。 OnPropertyChanges調用INotifyPropertyChanged 。 無論如何,我在這里偷工減料:
public YourViewModel : YourViewModelBase
{
private ObservableCollection<A> yourItems_ = new ObservableCollection<A>();
public ObservableCollection YourItems {
get { return yourItems_;}
set { if( yourItems_!=value ) {
_yourItems = value;
OnPropertyChanged();
}
return _yourItems;
}
}
}
然后在xaml中,您只需綁定到屬性YourItems並在數據模型上設置displaymember。
<UserControl.....>
<UserControl.DataContext><vm:YourViewModel/></UserControl.DataContext>
<Grid>
<Grid.RowDefinition="Auto"/>
<Grid.RowDefinition="Auto"/>
<Grid.RowDefinition="*"/>
<Grid/>
<ListBox Grid.RowDefinition="0" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
<ListBox Grid.RowDefinition="1" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
</UserControl>
請注意,您可以編輯模板以獲取商品的另一種視覺表示形式,除非您有一個覆蓋.ToString()的類,否則使用DisplayMamberPath會將其作為字符串添加到列表框演示文稿中。 方法。
如果需要過濾同一項目源,請查看ICollectionView 。
希望能幫助到你,
干杯,
施蒂安
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.