gpt4 book ai didi

WPF DataGrid 多选绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 12:39:59 25 4
gpt4 key购买 nike

我有一个启用多选的数据网格。我需要更改 View 模型中的选择。但是,SelectedItems 属性是只读的,不能直接绑定(bind)到 View 模型中的属性。那么我如何向 View 发出选择已更改的信号?

最佳答案

安迪是正确的。 DataGridRow.IsSelected是一个依赖属性,可以通过数据绑定(bind)来控制 ViewModel 中的选择。以下示例代码演示了这一点:

<Window x:Class="DataGridMultiSelectSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tk="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
Title="Window1" Height="300" Width="300">
<StackPanel>
<tk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" EnableRowVirtualization="False">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</tk:DataGrid.Columns>
<tk:DataGrid.RowStyle>
<Style TargetType="tk:DataGridRow">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</tk:DataGrid.RowStyle>
</tk:DataGrid>
<Button Content="Select Even" Click="Even_Click" />
<Button Content="Select Odd" Click="Odd_Click" />
</StackPanel>
</Window>
<小时/>
using System.ComponentModel;
using System.Windows;

namespace DataGridMultiSelectSample
{
public partial class Window1
{
public Window1()
{
InitializeComponent();
DataContext = new[]
{
new MyViewModel {Value = "Able"},
new MyViewModel {Value = "Baker"},
new MyViewModel {Value = "Charlie"},
new MyViewModel {Value = "Dog"},
new MyViewModel {Value = "Fox"},
};
}

private void Even_Click(object sender, RoutedEventArgs e)
{
var array = (MyViewModel[]) DataContext;
for (int i = 0; i < array.Length; ++i)
array[i].IsSelected = i%2 == 0;
}

private void Odd_Click(object sender, RoutedEventArgs e)
{
var array = (MyViewModel[])DataContext;
for (int i = 0; i < array.Length; ++i)
array[i].IsSelected = i % 2 == 1;
}
}

public class MyViewModel : INotifyPropertyChanged
{
public string Value { get; set; }

private bool mIsSelected;
public bool IsSelected
{
get { return mIsSelected; }
set
{
if (mIsSelected == value) return;
mIsSelected = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
}
}

public event PropertyChangedEventHandler PropertyChanged;
}
}

请务必设置EnableRowVirtualisation="False"在 DataGrid 元素上,否则存在 IsSelected 绑定(bind)不正常的风险。

关于WPF DataGrid 多选绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2615271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com