【问题标题】:Make certain rows unselectable in DataGrid from ViewModel使某些行在 ViewModel 中的 DataGrid 中不可选择
【发布时间】:2014-01-04 15:23:52
【问题描述】:

我正在按照 MVVM 模式构建 WPF 客户端。客户端使用 wpf DataGrid 来显示一些具有一些复杂分组要求的数据。我没有尝试找到一种方法在网格中显示所有这些分组,而是简单地为组页眉和页脚生成合成条目。

这一切正常,但它给我留下了一个问题,即我的 DataGrid 中有不应选择的行。我希望我可以控制视图模型的选择,但这似乎不起作用。我创建了一个示例项目来说明问题。

App.xaml

<Application x:Class="TestMVVM.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:vm="clr-namespace:TestMVVM.ViewModel"
         StartupUri="MainWindow.xaml">
  <Application.Resources>
    <ResourceDictionary>
        <vm:MainViewModel x:Key="MainViewModel"/>
    </ResourceDictionary>
  </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="TestMVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" DataContext="{StaticResource MainViewModel}">
  <Grid>
    <DataGrid ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}" IsSynchronizedWithCurrentItem="True"
              AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" SelectionUnit="FullRow">
        <!-- In the real app I use Style triggers here to highlight title and total rows and make them unselectable from the mouse,
             but you can still select them via the keyboard and when the grid is initially displayed it's on an invalid row -->
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Count" Binding="{Binding Count}"/>
        </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

MyItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestMVVM.Model
{
  public class MyItem
  {
    public MyItem(string name, int count)
    {
        Name = name;
        Count = count;
    }

    public string Name { get; private set; }
    public int Count { get; private set; }
  }

  public class MyItemTitle
  {
    public MyItemTitle(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
  }

  public class MyItemTotal
  {
    public MyItemTotal(string name, int total)
    {
        Name = name;
        Count = total;
    }

    public string Name { get; private set; }
    public int Count { get; private set; }
  }
}

MainViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using TestMVVM.Model;

namespace TestMVVM.ViewModel
{
  public class MainViewModel : INotifyPropertyChanged
  {
    private object _mySelectedItem;
    private int _lastIndex = -1;

    public MainViewModel()
    {
        var myItems = new List<object> {
            new MyItemTitle("Top Title"),
            new MyItemTitle("Subtitle"),
            new MyItem("Real Item", 1),
            new MyItem("Second Real Item", 4),
            new MyItemTotal("Subtitle totals", 5),
            new MyItem("Third Real Item", 11),
            new MyItemTotal("Top Title Totals", 16)
        };

        // Initially I used a List<> here but I thought maybe ObservableCollection
        // might make a difference.  As you can see, it does not.
        MyItems = new ObservableCollection<object>(myItems);
    }

    public IList<object> MyItems { get; private set; }

    public object MySelectedItem
    {
        get { return _mySelectedItem; }
        set
        {
            SetValidItem(value);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void SetValidItem(object value)
    {
        var newIndex = MyItems.IndexOf(value);

        if (newIndex == _lastIndex) return;  // no change, doubt this can happen

        if (IsItemValid(value))
        {
            _mySelectedItem = value;
            _lastIndex = newIndex;

            return;                         // selection worked as DataGrid expected
        }

        if (newIndex > _lastIndex)          // selection going down the grid
        {
            for (var i = newIndex + 1; i < MyItems.Count; ++i)
            {
                if (IsItemValid(MyItems[i]))
                {
                    _mySelectedItem = MyItems[i];
                    _lastIndex = i;
                }
            }
        }
        else if (newIndex < _lastIndex)    // selection going up the grid
        {
            for (var i = newIndex - 1; i > -1; --i)
            {
                if (IsItemValid(MyItems[i]))
                {
                    _mySelectedItem = MyItems[i];
                    _lastIndex = i;
                }
            }
        }

        // three possible scenarios when we get here:
        //   1) selection went up higher than selected in grid
        //   2) selection went down lower than selected in grid
        //   3) no valid higher/lower item was found so we keep the previous selection
        // in any of those cases we need to raise an event so the grid knows
        // that SelectedItem has moved

        RaiseOnMySelectedItemChanged();

        // I checked in the debugger and the event fired correctly and the DataGrid
        // called the getter again with the correct value.  The grid seemed to ignore
        // it though so I thought I could force the issue with this.  This doesn't seem
        // to do anything either (I even tried collectionView.MoveCurrentToLast())
        var collectionView = CollectionViewSource.GetDefaultView(MyItems);
        collectionView.MoveCurrentTo(_mySelectedItem);
    }

    private bool IsItemValid(object value)
    {
        return value is MyItem;
    }

    private void RaiseOnMySelectedItemChanged()
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            var args = new PropertyChangedEventArgs("MySelectedItem");

            handler(this, args);
        }
    }
  }
}

【问题讨论】:

    标签: c# wpf xaml mvvm wpfdatagrid


    【解决方案1】:

    1.解决此问题的一种方法是扩展DataGrid。然后在DataGridExtended 中确定是否需要从选择中跳过某些RowCell(可能将焦点移动到下一个单元格或下一行)。加工部分很简单。更难的是获取单元格或行。这是一篇如何做到这一点的帖子: How to get a cell from DataGrid?

    在您的 ViewModel 或模型中创建将项目标记为不可选择的属性,并在 DataGridExtended 中对其进行响应。

    2.关于这个主题还有一篇有趣的帖子可能对你有用,或者是一个额外的帮助者。它基本上创建了一种样式以使该行无法聚焦。 Making a row non-focusable in a WPF datagrid

    3.您可以在后面的代码中直接响应和取消选择事件。与(第 2 部分)一起,这可能会奏效。这是另一个如何开始的链接:http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing&referringTitle=Tips%20%26%20Tricks

    【讨论】:

    • 我已经在使用 2,但这只会阻止鼠标选择(在代码的注释中提到过)。 1 是我想到的,但我希望这可以完全从视图模型中完成。我真的不明白为什么这不起作用,因为它看起来应该。至于 3,我没有代码背后的可能性,因为在真正的应用程序中,DataGrid 是 DataTemplate 定义的一部分。无论如何,感谢您的回答。如果一周左右没有人提出更好的建议,我会接受你的第一名。
    • 对不起,我错过了你在代码中的评论。这是另一个想法,听起来可能很疯狂,但还不错。我实际上不得不在大约 3 年前做类似的事情。用户想要一个网格,但其样式和要求不适合常规网格。我构建了一个用户控件,它由一个堆栈面板组成,其中每一行都是另一个用户控件,由单元格(文本框或另一个控件)组成。现在有了这个,您可以在 ViewModel 中执行所有逻辑并在自定义复合用户控件的绑定中响应它(只是另一个想法)
    • 我最终创建了一个特殊的网格,它需要一个额外的属性来告诉它是否应该选择一行。这样我就不必在后面做任何代码,视图模型逻辑仍在视图模型中。
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    相关资源
    最近更新 更多