首页 > 其他分享 >WPF datagrid multiselect via inheritance from behavior

WPF datagrid multiselect via inheritance from behavior

时间:2024-12-04 23:55:41浏览次数:7  
标签:via inheritance void get System datagrid new using public

public class DatagridMultiSelectBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
    }


    public IEnumerable SelectedItems
    {
        get { return (IEnumerable)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SelectedItems.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
            typeof(DatagridMultiSelectBehavior),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}











 <behavior:Interaction.Behaviors>
     <local:DatagridMultiSelectBehavior/>
 </behavior:Interaction.Behaviors>
 <behavior:Interaction.Triggers>
     <behavior:EventTrigger EventName="SelectionChanged">
         <behavior:InvokeCommandAction Command="{Binding SelectedCommand}"
                                       CommandParameter="{Binding Path=SelectedItems,ElementName=dg}"/>
     </behavior:EventTrigger>
 </behavior:Interaction.Triggers>
 <DataGrid.Columns>







        private void SelectedCommandExecuted(object obj)
        {
            var itemsList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if (itemsList == null || !itemsList.Any())
            {
                MessageBox.Show("Nothing selected!");
                return;
            }
            SelectedBooks = new ObservableCollection<Book>(itemsList);
        }

 

 

 

 

 

 

 

 

//xaml
<Window x:Class="WpfApp51.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp51"
        WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="{x:Type Button}">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="FontWeight" Value="Normal"/>
            <Setter Property="Width" Value="200"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                    <Setter Property="FontSize" Value="50"/>
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="Width" Value="550"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style TargetType="{x:Type GridSplitter}">
            <Setter Property="Width" Value="100"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load"
                    Command="{Binding LoadCommand}" />
            <Button Content="Export Selected"                   
                    Command="{Binding ExportSelectedCommand}"
                    CommandParameter="{Binding SelectedItems,ElementName=dg}"/>
        </ToolBar>
        <DataGrid x:Name="dg"
                  Grid.Row="1"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectionMode="Extended"
                  VirtualizingPanel.IsContainerVirtualizable="True"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.CacheLength="1"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  CanUserAddRows="False"
                  AutoGenerateColumns="False"
                  >
            <behavior:Interaction.Behaviors>
                <local:DatagridMultiSelectBehavior/>
            </behavior:Interaction.Behaviors>
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:InvokeCommandAction Command="{Binding SelectedCommand}"
                                                  CommandParameter="{Binding Path=SelectedItems,ElementName=dg}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="200" />
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}" Width="300"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="200"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}" Width="200"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic}" Width="200"/>
            </DataGrid.Columns>            
        </DataGrid>
    </Grid>
</Window>









//cs
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;
using Microsoft.Win32;
using System.IO;

namespace WpfApp51
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitCommands();
        }

        private void InitCommands()
        {
            ExportSelectedCommand = new DelCommand(ExportSelectedCommandExecuted);
            SelectedCommand = new DelCommand(SelectedCommandExecuted);
        }

        private void SelectedCommandExecuted(object obj)
        {
            var itemsList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if (itemsList == null || !itemsList.Any())
            {
                MessageBox.Show("Nothing selected!");
                return;
            }
            SelectedBooks = new ObservableCollection<Book>(itemsList);
        }

        private void ExportSelectedCommandExecuted(object obj)
        {
            if (SelectedBooks == null || !SelectedBooks.Any())
            {
                MessageBox.Show("Nothing seletced!");
                return;
            }
            var msgResult = MessageBox.Show($"Are you sure to export selected {SelectedBooks.Count} items","Selected Items",
                MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.Yes);
            if(msgResult!=MessageBoxResult.Yes)
            {
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Json Files|*.json|All Files|*.*";
            dialog.FileName = $"Json_{DateTime.UtcNow.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.json";
            if (dialog.ShowDialog() == true)
            {
                string jsonStr = JsonConvert.SerializeObject(SelectedBooks, Formatting.Indented);
                File.WriteAllText(dialog.FileName, jsonStr);

            }
        }

        private void InitData()
        {
            BooksCollection = new ObservableCollection<Book>();
            for (int i = 0; i < 100000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                    Name = $"Name_{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic_{i + 1}"
                });
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

        private ObservableCollection<Book> selectedBooks;
        public ObservableCollection<Book> SelectedBooks
        {
            get
            {
                return selectedBooks;
            }
            set
            {
                if (value != selectedBooks)
                {
                    selectedBooks = value;
                    OnPropertyChanged(nameof(SelectedBooks));
                }
            }
        }

        public DelCommand ExportSelectedCommand { get; set; }
        public DelCommand SelectedCommand { get; set; }
    }

    public class DatagridMultiSelectBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }


        public IEnumerable SelectedItems
        {
            get { return (IEnumerable)GetValue(SelectedItemsProperty); }
            set { SetValue(SelectedItemsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedItems.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
                typeof(DatagridMultiSelectBehavior),
                new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    }

    public class Book
    {
        public int Id { get; set; }
        public string ISBN { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    public class DelCommand : ICommand
    {
        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCommand(Action<object> executeValue, Predicate<object> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

 

标签:via,inheritance,void,get,System,datagrid,new,using,public
From: https://www.cnblogs.com/Fred1987/p/18587493

相关文章

  • heritage、legacy和inheritance的区别
    heritage、legacy和inheritance都表示从祖先处得到的物品或财富。他们的区别是:heritage不是财物,是文化、历史、语言、遗迹这样的东西。如:Theparliamenthaspassedalawtopreserveculturalheritage.(国会通过了一部旨在保护文化遗产的法律)legacy也不是财物,他是一种对后世或......
  • winform DataGridView的一些初始化
    System.Windows.Forms.DataGridViewCellStyledataGridViewCellStyle1=newSystem.Windows.Forms.DataGridViewCellStyle();dataGridViewCellStyle1.Alignment=System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;dataGridViewCell......
  • WPF Datagrid AutoScroll via behavior
    publicclassDataGridAutoScrollBehavior:Behavior<DataGrid>{protectedoverridevoidOnAttached(){base.OnAttached();AssociatedObject.SelectionChanged+=AssociatedObject_SelectionChanged;}privatevoidAssociated......
  • WPF Datagrid DataGridTemplateColumn DataTemplate UserControl MVVM
    //uercontrol<UserControlx:Class="WpfApp47.ImgTbk"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc=&......
  • 【论文阅读】Zero-Reference Low-Light Enhancement via Physical Quadruple Priors(CV
    概要任务领域:低光增强;零样本/无参考;RGB域针对问题:零参考是成功的,但是缺少光照概念,依赖手工设置。解决方法:基于Kubelka-Munk理论,设计物理四先验作为低光和正常光的不变要素,再利用生成模型将先验转为图像。主要创新:物理四先验的设计;先验到图像的映射。最终表现:优于大多数无监......
  • WPF mouse move via mosuedown,mousemove and mouseup
    <Windowx:Class="WpfApp42.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • 【C++】继承(inheritance)
    引入假设我们有一个动物类classAnimal{public:intage;voideat(){std::cout<<"吃东西!"<<std::endl;}};又想写一个狗类,它也有年龄,也会吃,除此之外还有种类classDog{public:constchar*kind;intage;voideat(){......
  • Winform控件基础与进阶----DataGridView
    Winform控件基础之封装一个通用的DataGridView操作类1、创建Winform项目2、创建公共控件操作文件夹3、主界面1、控件布局2、提取通用方法3、静态方法类实现4、其他工具类实现1、JsonHelper工具类实现2、TxtOperateHelper工具类实现5、数据模型实现1、创建表结构模型2......
  • WPF ListBox IsSynchronizedWithCurrentItem True ScrollIntoView via behavior CallM
    <ListBoxGrid.Column="0"ItemContainerStyle="{StaticResourcelbxItemContainerStyle}"ItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"IsSynchronizedWith......
  • 论文研读——《RF-Diffusion: Radio Signal Generation via Time-Frequency Diffusion
    本文的是有关无线电信号生成的一篇文章。目录论文简介名词补充现有RF数据生成模型论文贡献RF-Diffusion时频扩散时频扩散——正向销毁过程时频扩散——正向销毁过程时频扩散——逆向恢复过程  时频扩散——条件生成分层扩散Transformer分层扩散Transformer——......