如何将ListBox的SelectedItem绑定到另一个ListBox的SelectedItem属性?

时间:2014-03-05 17:50:26

标签: c# .net wpf binding listbox

我的UI中有一个绑定到List<Notification> Notifications { get; set; }的ListBox:

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

通知有一个与之关联的过滤器标题:

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

我的UI有另一个绑定到List<LogFilter> Filters { get; set; }的ListBox:

<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。你怎么能通过绑定来做到这一点?

2 个答案:

答案 0 :(得分:1)

首先,您需要将第一个listBox的SelectedValuePath设置为FilterTitle

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

使用SelectedValue与第一个列表框的ElementName绑定。此外,您还需要在此设置SelectedValuePathTitle

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

答案 1 :(得分:1)

正如您在之前的问题的其他答案中所提到的,您应该考虑在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);
     }
 }