簡體   English   中英

從一個列表框綁定到另一個列表框?

[英]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


ObservableCollectionObservableCollection ,另一個答案是使用ObservableCollection ,除非數組是動態變化的,否則不需要。 否則可以使用任何數組。 根據從虛擬機加載的數據,它可能需要遵循INotifyPropertyChanged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM