如何从MVVM WPF项目中的DataGrid
中选择多个项目?
答案 0 :(得分:98)
您只需添加自定义依赖项属性即可:
public class CustomDataGrid : DataGrid
{
public CustomDataGrid ()
{
this.SelectionChanged += CustomDataGrid_SelectionChanged;
}
void CustomDataGrid_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
this.SelectedItemsList = this.SelectedItems;
}
#region SelectedItemsList
public IList SelectedItemsList
{
get { return (IList)GetValue (SelectedItemsListProperty); }
set { SetValue (SelectedItemsListProperty, value); }
}
public static readonly DependencyProperty SelectedItemsListProperty =
DependencyProperty.Register ("SelectedItemsList", typeof (IList), typeof (CustomDataGrid), new PropertyMetadata (null));
#endregion
}
现在您可以在XAML中使用此dataGrid
:
<Window x:Class="DataGridTesting.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:DataGridTesting.CustomDatagrid"
Title="MainWindow"
Height="350"
Width="525">
<DockPanel>
<local:CustomDataGrid ItemsSource="{Binding Model}"
SelectionMode="Extended"
AlternatingRowBackground="Aquamarine"
SelectionUnit="FullRow"
IsReadOnly="True"
SnapsToDevicePixels="True"
SelectedItemsList="{Binding TestSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DockPanel>
</Window>
我的ViewModel
:
public class MyViewModel : INotifyPropertyChanged
{
private static object _lock = new object ();
private List<MyModel> _myModel;
public IEnumerable<MyModel> Model { get { return _myModel; } }
private IList _selectedModels = new ArrayList ();
public IList TestSelected
{
get { return _selectedModels; }
set
{
_selectedModels = value;
RaisePropertyChanged ("TestSelected");
}
}
public MyViewModel ()
{
_myModel = new List<MyModel> ();
BindingOperations.EnableCollectionSynchronization (_myModel, _lock);
for (int i = 0; i < 10; i++)
{
_myModel.Add (new MyModel
{
Name = "Test " + i,
Age = i * 22
});
}
RaisePropertyChanged ("Model");
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged (string propertyName)
{
var pc = PropertyChanged;
if (pc != null)
pc (this, new PropertyChangedEventArgs (propertyName));
}
}
我的模特:
public class MyModel
{
public string Name { get; set; }
public int Age { get; set; }
}
最后,这是MainWindow
:
public partial class MainWindow : Window
{
public MainWindow ()
{
InitializeComponent ();
this.DataContext = new MyViewModel ();
}
}
我希望这种干净的MVVM设计有所帮助。
答案 1 :(得分:26)
我要做的是使用Behaviors
创建System.Windows.Interactivity
。您必须在项目中手动引用它。
给定一个不公开SelectedItems
的控件,例如(ListBox,DataGrid)
您可以创建类似这样的行为类
public class ListBoxSelectedItemsBehavior : Behavior<ListBox>
{
protected override void OnAttached()
{
AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= AssociatedObjectSelectionChanged;
}
void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var array = new object[AssociatedObject.SelectedItems.Count];
AssociatedObject.SelectedItems.CopyTo(array, 0);
SelectedItems = array;
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable), typeof(ListBoxSelectedItemsBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public IEnumerable SelectedItems
{
get { return (IEnumerable)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
}
在XAML
Binding
我会i
这样xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
behaviors
而Behavior
是<ListBox>
<i:Interaction.Behaviors>
<behaviors:ListBoxSelectedItemsBehavior SelectedItems="{Binding SelectedItems, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
的命名空间类
DataContext
假设ListBox
的{{1}}在SelectedItems
中有ViewModel
属性,则会自动更新SelectedItems
。你已经封装了从event
订阅的View
,即
<ListBox SelectionChanged="ListBox_SelectionChanged"/>
如果需要,您可以将Behavior
类更改为DataGrid
类型。
答案 2 :(得分:18)
我在我的应用中使用此解决方案:
XAML:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectItemsCommand}" CommandParameter="{Binding Path=SelectedItems,ElementName=TestListView}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
在xaml文件的顶部,添加以下代码行:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
SelectedItemsCommand是ICommand类型,它在您的viewmodel中写入。
使用过的DLL:
System.Windows.Interactivity.dll
答案 3 :(得分:9)
使用WPF的默认DataGrid
,无法使用绑定,因为SelectedItem
- 属性可能导致SelectedItems
- 属性不是DependencyProperty。
获得所需内容的一种方法是注册DataGrid的SelectionChanged
- 事件,以更新存储所选项目的ViewModel的属性。
DataGrid的属性SelectedItems属于IList类型,因此您需要将列表中的项目强制转换为您的特定类型。
C#
public MyViewModel {
get{
return this.DataContext as MyViewModel;
}
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) {
// ... Get SelectedItems from DataGrid.
var grid = sender as DataGrid;
var selected = grid.SelectedItems;
List<MyObject> selectedObjects = selected.OfType<MyObject>().ToList();
MyViewModel.SelectedMyObjects = selectedObjects;
}
XAML
<Window x:Class="WpfApplication1.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">
<Grid>
<DataGrid
SelectionChanged="DataGrid_SelectionChanged"
/>
</Grid>
</Window>
答案 4 :(得分:2)
您可以在模型中添加“IsSelected”属性,并在行中添加一个复选框。
答案 5 :(得分:2)
您可以使用可重用的通用基类。这样,您就可以从代码和UI 中选择行。
这是我希望可以选择的示例类
public class SelectableItem<T> : System.ComponentModel.INotifyPropertyChanged
{
public SelectableItem(T item)
{
Item = item;
}
public T Item { get; set; }
bool _isSelected;
public bool IsSelected {
get {
return _isSelected;
}
set {
if (value == _isSelected)
{
return;
}
_isSelected = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("IsSelected"));
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
为可选类创建通用基类。设置IsSelected时,INotifyPropertyChanged会更新UI。
public class MySelectableItem: SelectableItem<MyClass>
{
public MySelectableItem(MyClass item)
:base(item)
{
}
}
创建可选择的类
ObservableCollection<MySelectableItem> MyObservableCollection ...
创建要绑定到
的属性MyObservableCollection = myItems.Select(x => new MySelectableItem(x));
设置比赛
<DataGrid
ItemsSource="{Binding MyObservableCollection}"
SelectionMode="Extended">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</DataGrid.Resources>
</DataGrid>
绑定到datagrid并在DataGridRow上添加一个样式,该样式绑定到MySelectedItem上的IsSelected propety
var selectedItems = MyObservableCollection.Where(x=>x.IsSelected).Select(y=>y.Item);
获取所选行/项目
MyObservableCollection[0].IsSelected = true;
选择行/项目
if(isset($_POST['submit1'])){
//do your code for form 1
}
if(isset($_POST['submit2'])){
//do your code for form 2
}
编辑---&GT; 当EnableRowVirtualization为真时,它似乎不起作用
答案 6 :(得分:0)
WPF DataGrid允许这样做。 只需将DataGrid.Rows.SelectionMode和DataGrid.Rows.SelectionUnit设置为&#34; Extended&#34;和&#34; CellOrRowHeader&#34;分别。这可以在Blend中完成,如我所包含的图像所示。这将允许用户使用shift或ctrl键继续选择,根据需要选择每个单元格,整行等。
答案 7 :(得分:0)
我正在处理的项目使用MVVM Light,我发现this blog post是最简单的解决方案。我在这里重复解决方案:
查看型号:
add() {
this.data.item.push({ title: 'pushed', config: { sizex: 1} });
}
XAML:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
...
public class SomeVm : ViewModelBase {
public SomeVm() {
SelectItemsCommand = new RelayCommand<IList>((items) => {
Selected.Clear();
foreach (var item in items) Selected.Add((SomeClass)item);
});
ViewCommand = new RelayCommand(() => {
foreach (var selected in Selected) {
// todo do something with selected items
}
});
}
public List<SomeClass> Selected { get; set; }
public RelayCommand<IList> SelectionChangedCommand { get; set; }
public RelayCommand ViewCommand { get; set; }
}