【问题标题】:Databinding Complex Object Models with WPF使用 WPF 对复杂对象模型进行数据绑定
【发布时间】:2013-02-04 21:21:57
【问题描述】:

我目前正在重构一些使用 C# 在 WPF 之上编写的旧代码。

我目前有一个如下所示的复合用户模型:

public class UserModel{
   public User User {get; set;}
   public List<Guid> Permissions {get; set;}
}

在此模型中,权限列表是授予模型引用的用户的权限 ID 的列表。

In my xaml for my user management screen I have a list of these models bound to a combo box and when the selection changes the selected item is bound to a Grid containing text boxes for the User property and an Items Control.

当页面加载时,此项目控件由绑定到系统中所有权限的复选框填充。我的问题是将权限列表绑定到项目控件中的复选框的最佳方法是什么?

项目控件的代码如下所示:

<ScrollViewer Grid.Row="7" Grid.Column="1">
  <ItemsControl ItemsSource={Binding}>
    <ItemsControl.ItemsTemplate>
        <DataTemplate>
            <Checkbox Content="{Binding Description}" IsChecked="{Binding IsSelected}"/>
        </DataTemplate>
    </ItemsControl.ItemsTemplate>
</ScrollViewer>

而权限的集合就是这个对象的一个​​List:

class SelectedPermission{
   public Guid PermissionId {get; set;}
   public string Description {get; set;}
   public bool IsSelected {get; set;}
 }

我最初的想法是在 SelectedPermission 集合上实现 INotifyPropertyChanged,当我绑定我的用户时,只需将 IsSelected 设置为 true,以获得授予所选用户的任何权限。但似乎应该有更好的方法。

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    我看不出你的方法有什么问题,你基本上是在创建一个 ViewModel 来包装权限。

    但是,我会更进一步,定义一个 Selectable ViewModel,这将是您可能拥有的任何其他基于 CheckBox 的选择屏幕的通用解决方案:

    public class Selectable<T>: ViewModelBase //ViewModelBase should Implement NotifyPropertyChanged.
    {
        private T _model;
        public T Model 
        {   get { return _model; }
            set 
            {
                _model = value;
                NotifyPropertyChange("Model");
            }
        }
    
        private bool _isSelected;
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                NotifyPropertyChange("IsSelected");
            }
        }
    
     }
    

    那么你可以这样做:

    public ObservableCollection<Selectable<Permission>> Permissions {get;set; } //etc.
    

    【讨论】:

    • 我试一试,我只是想可能有一种方法可以将 IsSelected 绑定到用户权限列表,而不是遍历 DataContext。
    • 你可以使用 LinQ。
    • 是的,但我认为在我的意思的 Xaml 中可能有办法做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2012-11-22
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    相关资源
    最近更新 更多