簡體   English   中英

如何將ListBox的SelectedItem綁定到另一個ListBox的SelectedItem屬性?

[英]How do you bind a ListBox's SelectedItem to another ListBox's SelectedItem's property?

我的UI中有一個ListBox,它綁定到List<Notification> Notifications { get; set; } List<Notification> Notifications { get; set; } List<Notification> Notifications { get; set; }

<ListBox ItemsSource="{Binding Notifications}"
         DisplayMemberPath="ServiceAddress"
         Name="NotificationsList"/>

通知具有與之關聯的過濾器標題:

public class Notification
{
    public string FilterTitle { get; set; }
    public string ServiceAddress { get; set; }
}

我的UI有另一個ListBox綁定到List<LogFilter> Filters { get; set; } List<LogFilter> Filters { get; set; } List<LogFilter> Filters { get; set; }

<ListBox ItemsSource="{Binding Filters}"
         DisplayMemberPath="Title"
         Name="FiltersList"/>

正如你可以猜到的,LogFilter包含一個標題:

public class LogFilter
{
    public string Title { get; set; }
}

當我在NotificationsList中選擇Notification時,我希望它根據Notification的FilterTitle和LogFilter的Title的映射在我的FiltersList中選擇相應的LogFilter。 你怎么能通過綁定來做到這一點?

首先,您需要將第一個listBox的SelectedValuePath設置為FilterTitle

<ListBox ItemsSource="{Binding Notifications}"
         DisplayMemberPath="ServiceAddress" 
         Name="NotificationsList"
         SelectedValuePath="FilterTitle"/>

使用ElementName綁定第一個列表框的SelectedValue 此外,您還需要在此處將SelectedValuePath設置為Title

<ListBox ItemsSource="{Binding Filters}"
         DisplayMemberPath="Title"
         Name="FiltersList"
         SelectedValuePath="Title"
         SelectedValue="{Binding SelectedValue, ElementName=NotificationsList, 
                                 Mode=OneWay}"/>

正如您在之前的問題的其他答案中所提到的,您應該考慮在ViewModel級別引入“Selected Item”的概念:

public class MyViewModel
{
     public List<Notification> Notifications {get;set;}

     //Here!
     public Notification SelectedNotification {get;set;} //INotifyPropertyChanged, etc here
}

然后將ListBox.SelectedItem綁定到:

<ListBox ItemsSource="{Binding Notifications}"
         SelectedItem="{Binding SelectedNotification}"
         DisplayMemberPath="ServiceAddress"/>

與其他ListBox相同:

<ListBox ItemsSource="{Binding Filters}"
         SelectedItem="{Binding SelectedFilter}"
         DisplayMemberPath="Title"/>

然后在更改SelectedNotification時在ViewModel級別找到適當的過濾器:

 private Notification _selectedNotification;
 public Notification SelectedNotification
 {
     get { return _selectedNotification; }
     set
     {
         _selectedNotification = value;
         NotifyPropertyChange("SelectedNotification");

         //here...
         if (value != null)     
             SelectedFilter = Filters.FirstOrDefault(x => x.Title == value.FilterTitle);
     }
 }

暫無
暫無

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

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