使用 MVVM 模式在 Telerik RadGridView 中查找所选项目

发布于 2024-11-18 06:37:22 字数 209 浏览 7 评论 0原文

我在我的应用程序中使用 Telerik RadGridView,它有一个 GridViewSelectColumn 项目,它允许我选择网格中的各种项目。我有一个对此选择进行操作的按钮,但不确定如何获取所选项目的列表。问题是我正在使用带有 Caliburn.Micro 的 MVVM 模式。我是否需要在视图中找到控件并遍历所选项目的列表?对于一项简单的任务来说,这似乎需要做很多工作。我将不胜感激任何想法。

I am using a Telerik RadGridView in my application and it has a GridViewSelectColumn item in it, which allows me to select various items in the grid. I have a button that operates on this selection, but am not sure how to get the list of selected items. The problem is that I am using an MVVM pattern with Caliburn.Micro. Do I need to find the control in the view and traverse the list of selected items? That seems like a lot of work for a simple task. I would appreciate any ideas.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

森林很绿却致人迷途 2024-11-25 06:37:22

Telerik 的 RadGridView 的问题是,它的 SelectedItem 集合是只读的,因此您无法将双向绑定到 SelectedItems。

解决此问题的方法是使用自定义行为在 RadGridView 和 ViewModels SelectedItem 集合之间进行同步

您可以使用此行为:

// Behavior for synchronizing a RadDataGrid's SelectedItems collection with a SelectedItems collection of the ViewModel (the Network)
// The problem is, that RadDataGrid.SelectedItems is a read-only collection and therefore cannot be used for two-way binding.

class SelectedSyncBehavior
    : Behavior<RadGridView>
{
    bool _collectionChangedSuspended = false;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
    }

    /// <summary>
    /// Getter/Setter for DependencyProperty, bound to the DataContext's SelectedItems ObservableCollection
    /// </summary>
    public INotifyCollectionChanged SelectedItems
    {
        get { return (INotifyCollectionChanged)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }

    /// <summary>
    /// Dependency Property "SelectedItems" is target of binding to DataContext's SelectedItems
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged), typeof(SelectedSyncBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    /// <summary>
    /// PropertyChanged handler for DependencyProperty "SelectedItems"
    /// </summary>
    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        INotifyCollectionChanged collection = args.NewValue as INotifyCollectionChanged;
        if (collection != null)
        {
            // Hook to the Network's SelectedItems
            collection.CollectionChanged += (target as SelectedSyncBehavior).ContextSelectedItems_CollectionChanged;
        }
    }

    /// <summary>
    /// Will be called, when the Network's SelectedItems collection changes
    /// </summary>
    void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (_collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        _collectionChangedSuspended = true;

        // Select and unselect items in the grid
        if (e.NewItems != null)
            foreach (object item in e.NewItems)
                AssociatedObject.SelectedItems.Add(item);

        if (e.OldItems != null)
            foreach (object item in e.OldItems)
                AssociatedObject.SelectedItems.Remove(item);

        _collectionChangedSuspended = false;
    }

    /// <summary>
    /// Will be called when the GridView's SelectedItems collection changes
    /// </summary>
    void GridSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (_collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        _collectionChangedSuspended = true;

        // Select and unselect items in the DataContext
        if (e.NewItems != null)
            foreach (object item in e.NewItems)
                (SelectedItems as IList).Add(item);

        if (e.OldItems != null)
            foreach (object item in e.OldItems)
                (SelectedItems as IList).Remove(item);

        _collectionChangedSuspended = false;
    }

}

将此行为与 RadGridView 一起使用,如下所示:

<i:Interaction.Behaviors>
   <behaviors:SelectedSyncBehavior SelectedItems="{Binding ViewModel.SelectedItems}" />
</i:Interaction.Behaviors>

The problem with Telerik's RadGridView is, that its SelectedItem collection is read-only, so you cannot bind two-way to SelectedItems.

A workaround for this is to use a custom Behavior to do the synchronization between RadGridView and your ViewModels SelectedItem collection

You may use this Behavior:

// Behavior for synchronizing a RadDataGrid's SelectedItems collection with a SelectedItems collection of the ViewModel (the Network)
// The problem is, that RadDataGrid.SelectedItems is a read-only collection and therefore cannot be used for two-way binding.

class SelectedSyncBehavior
    : Behavior<RadGridView>
{
    bool _collectionChangedSuspended = false;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
    }

    /// <summary>
    /// Getter/Setter for DependencyProperty, bound to the DataContext's SelectedItems ObservableCollection
    /// </summary>
    public INotifyCollectionChanged SelectedItems
    {
        get { return (INotifyCollectionChanged)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }

    /// <summary>
    /// Dependency Property "SelectedItems" is target of binding to DataContext's SelectedItems
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged), typeof(SelectedSyncBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    /// <summary>
    /// PropertyChanged handler for DependencyProperty "SelectedItems"
    /// </summary>
    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        INotifyCollectionChanged collection = args.NewValue as INotifyCollectionChanged;
        if (collection != null)
        {
            // Hook to the Network's SelectedItems
            collection.CollectionChanged += (target as SelectedSyncBehavior).ContextSelectedItems_CollectionChanged;
        }
    }

    /// <summary>
    /// Will be called, when the Network's SelectedItems collection changes
    /// </summary>
    void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (_collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        _collectionChangedSuspended = true;

        // Select and unselect items in the grid
        if (e.NewItems != null)
            foreach (object item in e.NewItems)
                AssociatedObject.SelectedItems.Add(item);

        if (e.OldItems != null)
            foreach (object item in e.OldItems)
                AssociatedObject.SelectedItems.Remove(item);

        _collectionChangedSuspended = false;
    }

    /// <summary>
    /// Will be called when the GridView's SelectedItems collection changes
    /// </summary>
    void GridSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (_collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        _collectionChangedSuspended = true;

        // Select and unselect items in the DataContext
        if (e.NewItems != null)
            foreach (object item in e.NewItems)
                (SelectedItems as IList).Add(item);

        if (e.OldItems != null)
            foreach (object item in e.OldItems)
                (SelectedItems as IList).Remove(item);

        _collectionChangedSuspended = false;
    }

}

Use this Behavior with RadGridViews like this:

<i:Interaction.Behaviors>
   <behaviors:SelectedSyncBehavior SelectedItems="{Binding ViewModel.SelectedItems}" />
</i:Interaction.Behaviors>
还在原地等你 2024-11-25 06:37:22

将 bool IsSelected 添加到集合中的项目:

 public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsSelected { get; set; }
    }

 private BindableCollection<Customer> _customers;
        public BindableCollection<Customer> Customers
        {
            get { return _customers; }
            set
            {
                _customers = value;
                NotifyOfPropertyChange(() => Customers);
            }
        }

示例代码 - bitbucket

下载

Add a bool IsSelected to the item in your collection:

 public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsSelected { get; set; }
    }

 private BindableCollection<Customer> _customers;
        public BindableCollection<Customer> Customers
        {
            get { return _customers; }
            set
            {
                _customers = value;
                NotifyOfPropertyChange(() => Customers);
            }
        }

sample code - bitbucket

download

つ可否回来 2024-11-25 06:37:22

这是 @Knasterbax 类的清理副本,具有显式私有修饰符和 null 传播:

// Behavior for synchronizing Telerik RadDataGrid's SelectedItems collection 
//  with a SelectedItems collection of the ViewModel.   
public class SelectedSyncBehavior : Behavior<RadGridView>
{
    private bool collectionChangedSuspended;
    public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems",
        typeof(INotifyCollectionChanged), typeof(SelectedSyncBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
    }

    public INotifyCollectionChanged SelectedItems
    {
        get { return (INotifyCollectionChanged)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }

    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        var collection = args.NewValue as INotifyCollectionChanged;
        if (collection == null) return;
        var selectedSyncBehavior = target as SelectedSyncBehavior;
        if (selectedSyncBehavior != null) collection.CollectionChanged += selectedSyncBehavior.ContextSelectedItems_CollectionChanged;
    }

    private void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        collectionChangedSuspended = true;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)
                AssociatedObject.SelectedItems.Add(item);

        if (e.OldItems != null)
            foreach (var item in e.OldItems)
                AssociatedObject.SelectedItems.Remove(item);

        collectionChangedSuspended = false;
    }

    private void GridSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        collectionChangedSuspended = true;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)
            {
                var list = SelectedItems as IList;
                list?.Add(item);
            }

        if (e.OldItems != null)
            foreach (var item in e.OldItems)
            {
                var list = SelectedItems as IList;
                list?.Remove(item);
            }

        collectionChangedSuspended = false;
    }

}

Here is a cleaned up copy of @Knasterbax's class with explicit private modifiers and null propagation:

// Behavior for synchronizing Telerik RadDataGrid's SelectedItems collection 
//  with a SelectedItems collection of the ViewModel.   
public class SelectedSyncBehavior : Behavior<RadGridView>
{
    private bool collectionChangedSuspended;
    public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems",
        typeof(INotifyCollectionChanged), typeof(SelectedSyncBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
    }

    public INotifyCollectionChanged SelectedItems
    {
        get { return (INotifyCollectionChanged)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }

    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        var collection = args.NewValue as INotifyCollectionChanged;
        if (collection == null) return;
        var selectedSyncBehavior = target as SelectedSyncBehavior;
        if (selectedSyncBehavior != null) collection.CollectionChanged += selectedSyncBehavior.ContextSelectedItems_CollectionChanged;
    }

    private void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        collectionChangedSuspended = true;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)
                AssociatedObject.SelectedItems.Add(item);

        if (e.OldItems != null)
            foreach (var item in e.OldItems)
                AssociatedObject.SelectedItems.Remove(item);

        collectionChangedSuspended = false;
    }

    private void GridSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (collectionChangedSuspended) return;    // Don't react recursively to CollectionChanged events

        collectionChangedSuspended = true;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)
            {
                var list = SelectedItems as IList;
                list?.Add(item);
            }

        if (e.OldItems != null)
            foreach (var item in e.OldItems)
            {
                var list = SelectedItems as IList;
                list?.Remove(item);
            }

        collectionChangedSuspended = false;
    }

}
紫竹語嫣☆ 2024-11-25 06:37:22

这是上面答案的清理版本。这会删除下划线,添加限定符、访问器、大括号等。

public class SelectedItemsBehavior : Behavior<RadGridView>
{
    private bool collectionChangedSuspended;

    /// <summary>
    /// Called after the behavior is attached to an AssociatedObject.
    /// </summary>
    /// <remarks>
    /// Override this to hook up functionality to the AssociatedObject.
    /// </remarks>
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SelectedItems.CollectionChanged += this.GridSelectedItemsCollectionChanged;
    }

    /// <summary>
    /// Getter/Setter for DependencyProperty, bound to the DataContext's SelectedItems ObservableCollection
    /// </summary>
    public INotifyCollectionChanged SelectedItems
    {
        get => (INotifyCollectionChanged)this.GetValue(SelectedItemsProperty);
        set => this.SetValue(SelectedItemsProperty, value);
    }

    /// <summary>
    /// Dependency Property "SelectedItems" is target of binding to DataContext's SelectedItems
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged), typeof(SelectedItemsBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    /// <summary>
    /// PropertyChanged handler for DependencyProperty "SelectedItems"
    /// </summary>
    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        INotifyCollectionChanged collection = args.NewValue as INotifyCollectionChanged;
        if (collection != null)
        {
            collection.CollectionChanged += ((SelectedItemsBehavior)target).ContextSelectedItemsCollectionChanged;
        }
    }

    /// <summary>
    /// Will be called, when the Network's SelectedItems collection changes
    /// </summary>
    private void ContextSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (this.collectionChangedSuspended)
        {
            return; 
        }

        this.collectionChangedSuspended = true;

        if (e.NewItems != null)
        {
            foreach (object item in e.NewItems)
            {
                this.AssociatedObject.SelectedItems.Add(item);
            }
        }

        if (e.OldItems != null)
        {
            foreach (object item in e.OldItems)
            {
                this.AssociatedObject.SelectedItems.Remove(item);
            }
        }

        this.collectionChangedSuspended = false;
    }

    /// <summary>
    /// Will be called when the GridView's SelectedItems collection changes
    /// </summary>
    private void GridSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (this.collectionChangedSuspended)
        {
            return;
        }

        this.collectionChangedSuspended = true;

        if (e.NewItems != null)
        {
            foreach (object item in e.NewItems)
            {
                ((IList)this.SelectedItems).Add(item);
            }
        }

        if (e.OldItems != null)
        {
            foreach (object item in e.OldItems)
            {
                ((IList)this.SelectedItems).Remove(item);
            }
        }

        this.collectionChangedSuspended = false;
    }
}

Here's a cleanup version of the answer above. This removes underscores, adds qualifiers, accessors, braces, etc.

public class SelectedItemsBehavior : Behavior<RadGridView>
{
    private bool collectionChangedSuspended;

    /// <summary>
    /// Called after the behavior is attached to an AssociatedObject.
    /// </summary>
    /// <remarks>
    /// Override this to hook up functionality to the AssociatedObject.
    /// </remarks>
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SelectedItems.CollectionChanged += this.GridSelectedItemsCollectionChanged;
    }

    /// <summary>
    /// Getter/Setter for DependencyProperty, bound to the DataContext's SelectedItems ObservableCollection
    /// </summary>
    public INotifyCollectionChanged SelectedItems
    {
        get => (INotifyCollectionChanged)this.GetValue(SelectedItemsProperty);
        set => this.SetValue(SelectedItemsProperty, value);
    }

    /// <summary>
    /// Dependency Property "SelectedItems" is target of binding to DataContext's SelectedItems
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged), typeof(SelectedItemsBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));

    /// <summary>
    /// PropertyChanged handler for DependencyProperty "SelectedItems"
    /// </summary>
    private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        INotifyCollectionChanged collection = args.NewValue as INotifyCollectionChanged;
        if (collection != null)
        {
            collection.CollectionChanged += ((SelectedItemsBehavior)target).ContextSelectedItemsCollectionChanged;
        }
    }

    /// <summary>
    /// Will be called, when the Network's SelectedItems collection changes
    /// </summary>
    private void ContextSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (this.collectionChangedSuspended)
        {
            return; 
        }

        this.collectionChangedSuspended = true;

        if (e.NewItems != null)
        {
            foreach (object item in e.NewItems)
            {
                this.AssociatedObject.SelectedItems.Add(item);
            }
        }

        if (e.OldItems != null)
        {
            foreach (object item in e.OldItems)
            {
                this.AssociatedObject.SelectedItems.Remove(item);
            }
        }

        this.collectionChangedSuspended = false;
    }

    /// <summary>
    /// Will be called when the GridView's SelectedItems collection changes
    /// </summary>
    private void GridSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (this.collectionChangedSuspended)
        {
            return;
        }

        this.collectionChangedSuspended = true;

        if (e.NewItems != null)
        {
            foreach (object item in e.NewItems)
            {
                ((IList)this.SelectedItems).Add(item);
            }
        }

        if (e.OldItems != null)
        {
            foreach (object item in e.OldItems)
            {
                ((IList)this.SelectedItems).Remove(item);
            }
        }

        this.collectionChangedSuspended = false;
    }
}
缱倦旧时光 2024-11-25 06:37:22

在某些情况下,您无法添加布尔值(例如 ObseravbleCollection。

请查看 这个解决方案。

There are a situation where you cannot add boolean (ObseravbleCollection for example.

Please take a look at this solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文