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