[英]Binding from one ListBox to another ListBox?
我試圖將一個ListBox
綁定到同一窗口內的另一個ListBox
。 左側的Listbox
具有可供選擇的數據。 但是我希望用戶能夠單擊左側列表框中的項目,並且那些相同的項目將顯示在右側的其他列表框中。
編輯:當然,您可以使用ElementName
將一個UI屬性綁定到另一個UI屬性(實際上是Dependency Property
),但是我建議將這些屬性綁定到一個視圖模型。 請參閱下面的簡化示例。
查看模型:
public ObservableCollection<ItemObject> Items { get; set; }
public ObservableCollection<ItemObject> SelectedItems { get; set; }
剩下:
<ListBox ItemsSource="{Binding Items}" SelectedItems="{Binding SelectedItems}" />
(請注意,實際上並沒有SelectedItems
依賴項屬性。請參閱類似的問題: 從MVVM WPF項目的DataGrid中選擇多個項目 )
對:
<ListBox ItemsSource="{Binding SelectedItems}" />
這很好。 此外,使用這種方法,可以輕松自定義右邊的列表(例如,使用CollectionView
排序,過濾...)。
private ICollectionView _collectionView;
private ICollectionView _CollectionView {
get { return _collectionView
?? (_collectionView = CollectionViewSource.GetDefaultView(SelectedItems)); }
}
public ICollectionView FilteredItems {
get { _CollecitionView.Filter(...); }
}
<ListBox ItemsSource={"Binding FilteredSelectedItems"} />
這種MVVM方法有時很費力,但最終被認為是有益的。
您命名第一個列表框,然后xaml上的任何其他控件將使用綁定的ElementName
屬性中的名稱綁定到該控件。
例如,有兩個列表框和一個文本框。 頂部的列表框具有多項選擇,而這些選擇顯示在下部的列表框中。 而文本框僅獲得選擇的第一項。
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<converters:PathToFilenameConverter x:Key="FilenameConverter" />
<x:Array x:Key="FileNames" Type="system:String">
<system:String>C:\Temp\Alpha.txt</system:String>
<system:String>C:\Temp\Beta.txt</system:String>
<system:String>C:\Temp\Gamma.txt</system:String>
</x:Array>
</StackPanel.Resources>
<ListBox Name="lbFiles"
SelectionMode="Multiple"
ItemsSource="{StaticResource FileNames}"
Margin="10"/>
<ListBox ItemsSource="{Binding SelectedItems, ElementName=lbFiles }" Margin="10" />
<TextBlock Text="{Binding SelectedItem,
ElementName=lbFiles,
Converter={StaticResource FilenameConverter}}"
Margin="10" />
</StackPanel>
注意...代碼使用綁定SelectedItems
為下列表框屬性,而不是SelectedItem
被使用TextBlock
。
ObservableCollection
說ObservableCollection
,另一個答案是使用ObservableCollection
,除非數組是動態變化的,否則不需要。 否則可以使用任何數組。 根據從虛擬機加載的數據,它可能需要遵循INotifyPropertyChanged
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.