2014-03-05 101 views
0

我在UI的列表框绑定到List<Notification> Notifications { get; set; }如何将ListBox的SelectedItem绑定到另一个ListBox的SelectedItem的属性?

<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 ItemsSource="{Binding Filters}" 
     DisplayMemberPath="Title" 
     Name="FiltersList"/> 

正如你所猜,一个LogFilter包含一个标题:

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

当我在我的NotificationsList中选择通知时,我希望它根据通知的FilterTitle和LogFilter的标题的映射在我的FiltersList中选择相应的LogFilter。你怎么能通过绑定来做到这一点?

回答

1

首先你需要为第一列表框设置SelectedValuePathFilterTitle的:

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

绑定使用ElementName第一列表框的SelectedValue用。还需要设置SelectedValuePathTitle这里还有:

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

但是现在,当您选择在第一个列表框中的通知,然后更改第二个列表框中的过滤器,它会取消选择您在第一个列表框中选择的通知,而这不是我之后的功能......我希望能够更改过滤器通知。那可能吗? – Alexandru

+1

无法正确识别您,但我认为您只需要单向绑定,即选择了任何通知时,相应的标题被选中,而不是相反。如果是这种情况,您需要在绑定时设置“Mode = OneWay”。在答案中更新。 –

+0

它仍然缺少一些东西,因为它似乎没有从第一个列表框中正确更新。所以,我在第一个列表框中有一个通知列表,当我选择一个时,更新第二个列表框。当我更改第二个列表框中的选择时,我希望它将第一个列表框中的FilterTitle数据项(选定通知的一部分)更改为我在第二个列表框中选择的过滤器。 PS,我感谢迄今为止的帮助! – Alexandru

1

正如在其他的答案中提到你前面的问题,你应该考虑在视图模型级别引入“所选项目”的概念:

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时:

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); 
    } 
} 
+0

啊,是的,这正是你之前谈论的。我现在看到它。 – Alexandru

+0

我正在尝试这个,但我似乎无法得到它的工作,但我可以告诉事件的解雇......我会尽快发布堆栈问题... – Alexandru

+0

http://stackoverflow.com /问题/ 22208875 /为什么,心不是 - 我的选择项,数据绑定,更新 – Alexandru

相关问题