简体   繁体   English

绑定在组合框的selectionchanged上检查wpf列表框中的复选框

[英]Binding Ischecked of a checkbox in wpf listbox on selectionchanged of the combobox

I have a combobox of customer and that customer can be in more than 1 categories so i used a listbox which contains check-boxes of all the categories... 我有一个客户组合框,该客户可以在1个以上的类别,所以我使用了一个列表框,其中包含所有类别的复选框...

On the selection change of the customer, the categories in which a particular customer is, should be checked and all the other categories should remain unchecked.. 关于客户的选择变更,应检查特定客户的类别,并且所有其他类别应保持未选中状态。

here is my .dbml file 这是我的.dbml文件

在此输入图像描述

Here is my xaml code of listbox... 这是我的列表框的xaml代码...

  <ListBox Height="113.88" Margin="399.342,125.543,424.66,0" Name="lst_category" VerticalAlignment="Top" SelectedValuePath="CategoryID">
            <ListBox.ItemTemplate>
                <HierarchicalDataTemplate>
                <CheckBox Content="{Binding CategoryName}"/>
            </HierarchicalDataTemplate></ListBox.ItemTemplate>
        </ListBox>

I think i should use relative source in the binding in Ischecked property of checkbox... But i dont know how to use it please help me out... If there is some other solution to this than do let me know.. Thanks in advance... 我想我应该在复选框的Ischecked属性中使用绑定中的相对源...但我不知道如何使用它请帮助我...如果还有其他一些解决方案,请告诉我..谢谢预先...

Solution 1: Create a class CategoryViewModel like this: 解决方案1:创建一个类CategoryViewModel,如下所示:

class CategoryViewModel : INotifyPropertyChanged
{
   public Category Category {get ... set ...}
   public bool IsChecked {get ... set ...} //true if Category belongs to currently selected contact
}

Bind your UI to a ViewModel class that contains a list of CategoryViewModel that gets computed whenever you change the Selected Contact. 将UI绑定到ViewModel类,该类包含每当您更改Selected Contact时计算的CategoryViewModel列表。

Basically: 基本上:

class ViewModel : INotifyPropertyChanged
{
   public Contact SelectedContact { get .... set ....}

   //list of all possible categories (the ones belonging to SelectedContact will have IsChecked true
   public ObservableCollection<CategoryViewModel> Categories 
   {
       get .... set ....
   }   
}

Bind your listbox above to ViewModel.Categories property. 将上面的列表框绑定到ViewModel.Categories属性。

SelectedContact should be bound to the currently selected contact. SelectedContact应绑定到当前选定的联系人。 When it changes, in the setter, you re-create Categories list. 当它发生变化时,在setter中重新创建Categories列表。

Solution 2: Use some converters (wouldn't recommend it thought, because it's not MVVM) 解决方案2:使用一些转换器(不推荐它,因为它不是MVVM)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM