首页 > 系统相关 >WPF customize DelegateCommand via implementation interface System.Windows.Input.ICommand and change

WPF customize DelegateCommand via implementation interface System.Windows.Input.ICommand and change

时间:2024-07-10 20:31:55浏览次数:10  
标签:ICommand execute via System private BooksList using public DelCmd

public class DelCmd : ICommand
{
    private readonly Action<Object> execute;
    private readonly Predicate<Object> canExecute;

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

    public DelCmd(Action<object> executeValue):this(executeValue,null)
    {
        
    }

    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);
    }
}

 

 

 

//xaml
<Window x:Class="WpfApp203.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:local="clr-namespace:WpfApp203"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load" Command="{Binding LoadCmd}"/>
            <Button Content="Save" Command="{Binding SaveCmd}" 
                    CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/>
            <Button Content="Clear" Command="{Binding ClearCmd}" CommandParameter="{Binding ElementName=gd}"/>
            
        </ToolBar>
        <DataGrid Grid.Row="1" x:Name="gd" 
                  ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            
        </DataGrid>
    </Grid>
</Window>





//xaml.cs
using Microsoft.Win32;
using Newtonsoft.Json;
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;
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;

namespace WpfApp203
{
    /// <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()
        {
            InitCmds();
            //InitData();
        }

        private void InitData()
        { 
            List<Book> bkList = new List<Book>();
            for (int i = 0; i < 10000000; i++)
            {
                bkList.Add(new Book
                {
                    Id = i + 1,
                    Name = $"Name_{i + 1}"
                });
            }
            BooksList = new ObservableCollection<Book>(bkList);
        }

        private void InitCmds()
        { 
            LoadCmd = new DelCmd(LoadCmdExecuted, LoadCmdCanExecute);
            ClearCmd = new DelCmd(ClearCmdExecuted, ClearCmdCanExecute);
        }

        private bool LoadCmdCanExecute(object obj)
        {
            return BooksList == null || !BooksList.Any();
        }

        private bool ClearCmdCanExecute(object obj)
        {
            return BooksList != null && BooksList.Any();
        }

        private void ClearCmdExecuted(object obj)
        {
            BooksList = null;
        }

        private void LoadCmdExecuted(object obj)
        {
            InitData();
        }

        private bool SaveCmdCanExecute(object obj)
        {
            return BooksList != null && BooksList.Any();
        }

        private void SaveCmdExecuted(object obj)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Json Files|*.json|All Files|*.*";
            if (dialog.ShowDialog() == true)
            {
                string fileName = dialog.FileName;
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                }
                string jsonStr = JsonConvert.SerializeObject(BooksList, Formatting.Indented);
                System.IO.File.AppendAllText(fileName, jsonStr);
            }
        }

        private DelCmd saveCmd;
        public DelCmd SaveCmd 
        {
            get
            {
                if(saveCmd == null)
                {
                    saveCmd = new DelCmd(SaveCmdExecuted, SaveCmdCanExecute);
                }
                return saveCmd;
            }
        }
        public DelCmd LoadCmd { get; set; }
        public DelCmd ClearCmd { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> booksList; 
        

        public ObservableCollection<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                booksList = value;
                OnPropertyChanged(nameof(BooksList));
            }
        }
    }

    public class DelCmd : ICommand
    {
        private readonly Action<Object> execute;
        private readonly Predicate<Object> canExecute;

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

        public DelCmd(Action<object> executeValue):this(executeValue,null)
        {
            
        }

        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);
        }
    }

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

 

 

 

 

 

 

 

 

 

 

 

 

标签:ICommand,execute,via,System,private,BooksList,using,public,DelCmd
From: https://www.cnblogs.com/Fred1987/p/18294938

相关文章

  • WPF MouseWheel MouseDown MouseUp MouseMove mapped in mvvm via behavior
    //xaml<Windowx:Class="WpfApp201.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • WPF single instance via mutex
    usingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Diagnostics.Eventing.Reader;usingSystem.Linq;usingSystem.Runtime.InteropServices;usingSystem.Threading;usingSystem.Threading.Tasks;usingS......
  • Towards Accurate and Robust Architectures via Neural Architecture Search
    基于网络架构搜索的准确性与鲁棒性结构研究论文链接:https://arxiv.org/abs/2405.05502项目链接:未开源Abstract为了保护深度神经网络免受对抗性攻击,对抗性训练因其有效性而受到越来越多的关注。然而,对抗训练的准确性和鲁棒性受到体系结构的限制,因为对抗训练通过调整隶属......
  • Bug记录|vivia主题|Hexo+GitHub搭建个人博客
    1.将本地SSH添加到远程github 中,之后关联远程或push出现以下错误:fatal:Notagitrepository(oranyoftheparentdirectories):.git解决方案:执行 gitinit。gitinit2.hexog无法成功运行,出现以下错误:TypeError:C:\Users\Maxence\Desktop\项目\MyBlog\Hexo......
  • Visual C++ generate uuid via UuidCreate and CoCreateGuid,get time now,write stri
    //ConsoleApplication3.cpp:Thisfilecontainsthe'main'function.Programexecutionbeginsandendsthere.//#pragmacomment(lib,"rpcrt4.lib")#include<windows.h>#include<chrono>#include<ctime>#include&l......
  • [论文阅读] Calligraphy Font Generation via Explicitly Modeling Location-Aware Gl
    Pretitle:CalligraphyFontGenerationviaExplicitlyModelingLocation-AwareGlyphComponentDeformationssource:TMM2023paper:https://ieeexplore.ieee.org/document/10356848code:None关键词:generativeadversarialnetworks,imageprocessing,imagesynth......
  • [HBM] HBM TSV (Through Silicon Via) 结构与工艺
    依公知及经验整理,原创保护,禁止转载。专栏《深入理解DDR》全文3300字。1概念1.1什么是HBMTSV使用TSV堆叠多个DDRDRAM成为一块HBM,成倍提高了存储器位宽,一条位宽相当于高速公路的一条车道,车道越多,在相同的车速下,传输运输量自然越大。1.2TSV优点(1)高密......
  • Cobra - Flags are parsed after rootCmd.Execute()
     root.go:funcinit(){rootCmd.PersistentFlags().BoolVarP(&enableLogging,"log","l",true,"Logginginformation")fmt.Println("*************************",enableLogging)}funcExecute(){err:......
  • MODEL COMPRESSION VIA DISTILLATION AND QUANTIZATION翻译
    摘要:深度神经网络(DNNs)继续取得重大进展,解决了从图像分类到翻译或增强学习的任务。这个领域的一个受到广泛关注的方面是在资源受限环境中(如移动或嵌入式设备)高效执行深度模型。本文聚焦于这一问题,并提出了两种新的压缩方法,这两种方法共同利用了权重量化和大型网络(称为“教师”网络)......
  • GSVA: Generalized Segmentation via Multimodal Large Language Models论文阅读笔记
    Motivation&AbsGeneralizedReferringExpressionSegmentation(GRES):相比于原始的RES任务,一个文本描述里可能出现多个需要分割的物体,或者没有需要分割的物体,难点在于建模不同实体之间复杂的空间关系,以及识别不存在的描述。现有的方法如LISA难以处理GRES任务,为此作者提出了GSV......