【发布时间】: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