IT评测·应用市场-qidao123.com
标题:
WPF DataGrid多选行数据并绑定属性
[打印本页]
作者:
络腮胡菲菲
时间:
2025-3-10 20:39
标题:
WPF DataGrid多选行数据并绑定属性
在WPF的第三方控件UI库中,有些DataGrid实现了但是又有一些没实现多选行绑定数据。所有我如今通过附加属性来实现。
起首,实现DataGrid多选附加属性类
/// <summary>
/// DataGrid多选附加属性
/// </summary>
public class DataGridSelectedItemsBehavior : Behavior<DataGrid>
{
public IList SelectedItems
{
get => (IList)GetValue(SelectedItemsProperty);
set => SetValue(SelectedItemsProperty, value);
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register(
nameof(SelectedItems),
typeof(IList),
typeof(DataGridSelectedItemsBehavior),
new PropertyMetadata(null));
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += DataGrid_SelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= DataGrid_SelectionChanged;
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItems = AssociatedObject.SelectedItems;
}
}
复制代码
ViewModel实现,这里我利用了CommunityToolkit.Mvvm来与界面交互,你可以自行选择。
public class MainViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<ClassA> items = new();
[ObservableProperty]
private IList selectedItems = newArrayList();
[RelayCommand]
private void ExcuteConfirm()
{
foreach (var item in SelectedItems.Cast<ClassA>())
{
}
}
}
复制代码
此中DataGrid要把SelectionMode设置为Extended(表示可以多个选中),SelectionUnit设置为FullRow(表示完整行可以选中,单击单位格都会选中该行)。在XAML中利用之前你先看看你是否通过NuGet安装
Microsoft.Xaml.Behaviors.Wpf。
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:local="clr-namespace:YourNamespace.Behaviors"
<DataGrid ItemsSource="{{Binding Items}}" SelectionMode="Extended" SelectionUnit="FullRow">
<i:Interaction.Behaviors>
<local:DataGridSelectedItemsBehavior
VisibleItems="{{Binding SelectedItems, Mode=OneWayToSource}}"/>
</i:Interaction.Behaviors>
</DataGrid><br>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4