`

WPF Custom Routed Event Example

wpf 
阅读更多

Following to How to: Create a RoutedCommand, which demonstrate how to use the Static field to create a RoutedEvent rather than reuse the System RoutedCommand. 

 

Based on that documentaion, and based on the discussion in my previous post - WPF the routed event and routed command, I have come up a slight modified version which demonstrate some alternatives to create Custom RoutedCommand.

 

Basically I am using the Dependency Property. 

 

    public RoutedCommand MyRoutedCommand
    {
      get {
        return (RoutedCommand)GetValue(MyRoutedCommandProperty); }
      set { SetValue(MyRoutedCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyRoutedCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyRoutedCommandProperty =
        DependencyProperty.Register("MyRoutedCommand", typeof(RoutedCommand), typeof(MainWindow), new UIPropertyMetadata(null));
 

 

Since the CommandBinding Property Element does not accept BindingExtension, so you cannnot write as such 

 

 

    <Window.CommandBindings>
        <CommandBinding
            Command="MyRoutedCommand"
            CanExecute="MyRoutedCommandCanExecute"
            Executed="MyRoutedCommandExecuted"
            >
            
            
        </CommandBinding>
    </Window.CommandBindings>
 

But you can do the same via the code. here is the code. 

private void InitializeCommand()
{

      MyRoutedCommand = new RoutedCommand("MyRoutedCommand", this.GetType());
      // this is with the code to use the command binding
      CommandBinding binding = new CommandBinding();
      binding.Command = MyRoutedCommand;
      binding.CanExecute += new CanExecuteRoutedEventHandler(MyRoutedCommandCanExecute);
      binding.Executed += new ExecutedRoutedEventHandler(MyRoutedCommandExecuted);
      this.CommandBindings.Add(binding);
}
 

You may provide your own handler to CanExecute and Executed.

 

    void MyRoutedCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
      MessageBox.Show("This is the command window");
    }

    void MyRoutedCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
      //throw new NotImplementedException();
      e.CanExecute = true;
    }

 

Below is the main code (xaml parts) -- it contains the code of my enhancement as well as the original version from MSDN

 

<Window x:Class="CommandExecutions.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CommandExecutions"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        >
   
    <Window.CommandBindings>

        <CommandBinding Command="{x:Static local:MainWindow.CustomRoutedCommand}"
                        Executed="ExecuteCustomCommand"
                        CanExecute="CanExecuteCustomCommand" />
    </Window.CommandBindings>
    <StackPanel>
        <Button Name="myButton" Command="{Binding Path=MyRoutedCommand}" CommandTarget="{Binding RelativeSource={RelativeSource Self}}" Content="{Binding Path=ButtonContext}"/>
        <Button Name="MyButton2" Command="{x:Static local:MainWindow.CustomRoutedCommand}" Content="CustomRoutedCommand" />
    </StackPanel>
</Window>
 

And below is the code-behind file. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 System.ComponentModel;
using System.Diagnostics;

namespace CommandExecutions
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window,INotifyPropertyChanged
  {
    public MainWindow()
    {
      InitializeComponent();
      InitializeCommand();
      this.ButtonContext = "New Value";
    }
    private void InitializeCommand()
    {

      MyRoutedCommand = new RoutedCommand("MyRoutedCommand", this.GetType());
      // this is with the code to use the command binding
      CommandBinding binding = new CommandBinding();
      binding.Command = MyRoutedCommand;
      binding.CanExecute += new CanExecuteRoutedEventHandler(MyRoutedCommandCanExecute);
      binding.Executed += new ExecutedRoutedEventHandler(MyRoutedCommandExecuted);
      this.CommandBindings.Add(binding);
      //this.myButton.CommandBindings.Add(binding);

      // you can do the same with Xaml code 
      /*
    <Window.CommandBindings>
        <CommandBinding
            Command="MyRoutedCommand"
            CanExecute="MyRoutedCommandCanExecute"
            Executed="MyRoutedCommandExecuted"
            >
            
            
        </CommandBinding>
    </Window.CommandBindings>
       */
    }

    void MyRoutedCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
      MessageBox.Show("This is the command window");
    }

    void MyRoutedCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = true;
    }
    
    public RoutedCommand MyRoutedCommand
    {
      get {
        return (RoutedCommand)GetValue(MyRoutedCommandProperty); }
      set { SetValue(MyRoutedCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyRoutedCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyRoutedCommandProperty =
        DependencyProperty.Register("MyRoutedCommand", typeof(RoutedCommand), typeof(MainWindow), new UIPropertyMetadata(null));


    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
      var temp = PropertyChanged;
      if (temp != null)
      {
        temp(this, new PropertyChangedEventArgs(propertyName));
      }
    }

    public static RoutedCommand CustomRoutedCommand = new RoutedCommand();

    private void ExecuteCustomCommand(object sender_, ExecutedRoutedEventArgs e)
    {
      MessageBox.Show("Custom Command Executed");
    }

    private void CanExecuteCustomCommand(Object sender_, CanExecuteRoutedEventArgs e)
    {
      Control target = e.Source as Control;
      if (target != null)
      {
        e.CanExecute = true;
      }
      else
      {
        e.CanExecute = false;
      }
    }

  }
}
 
分享到:
评论

相关推荐

    WpfExample.rar

    标题中的“WpfExample.rar”是一个压缩包,包含了一个WPF项目的源代码,它展示了如何利用WPF的布局系统来创建一个能够自适应大小变化的界面。描述中提到,这个示例将帮助初学者理解如何通过WPF的容器来实现灵活的...

    WPF实例(实例比较多)

    WPFBasic_CustomControl WPFBasic_DataBinding WPFBasic_DemoWithXAML WPFBasic_DependencyPropertiesDemo WPFBasic_DependencySystem WPFBasic_Documents WPFBasic_Drawing WPFBasic_Interaction WPFBasic_Printing...

    WPF纯MVVM事件绑定+事件参数 完美示例

    首先,要实现事件绑定,我们需要引用`System.Windows.Interactivity`命名空间,这是WPF Blend SDK的一部分,提供了`EventTrigger`和`InvokeCommandAction`等类,让我们能够在XAML中绑定事件到ViewModel的命令。...

    WPF WEBROWSER EVENT NEWWINDOW

    WPF WEBROWSER EVENT NEWWINDOW

    CustomControl

    在Windows Presentation Foundation (WPF) 中,自定义控件(CustomControl)是为满足特定设计需求而创建的用户界面元素。这种控件允许开发者扩展已有的控件或创建全新的控件,以提供独特的功能和外观。`Custom...

    wpf之loading加载动画

    在Windows Presentation Foundation (WPF) 中,开发人员可以利用丰富的图形和动画功能来创建美观且交互性强的应用程序。"wpf之loading加载动画" 主题主要涵盖了如何在WPF应用中实现加载或等待动画,以提供更好的用户...

    NotificationDemoWPF自定义通知窗体样式

    【标题】"NotificationDemoWPF自定义通知窗体样式"主要涉及的是在Windows Presentation Foundation (WPF) 平台上创建自定义的通知窗口。WPF是.NET Framework的一部分,它提供了丰富的用户界面设计工具和功能,允许...

    WPF虚拟键盘,数字键盘

    总的来说,使用WPF和Keybd_event函数开发虚拟键盘是一项涉及用户界面设计、API调用和事件处理的任务。通过理解这些概念和技术,你可以创建出一款功能齐全且用户体验良好的数字键盘,适用于各种需要键盘输入的场景。...

    WPF自定义软键盘

    【WPF自定义软键盘】是一种专为WPF(Windows Presentation Foundation)应用程序设计的触摸屏虚拟输入设备。在没有物理键盘的环境下,如平板电脑或触摸显示器,这种虚拟键盘提供了输入文字的功能,尤其适用于触控...

    深入学习WPF及其新技术

    此外,WPF还提供了强大的事件处理机制,如根事件(Routed Event)和命令(Command),使得交互逻辑更加模块化和易于管理。 在WPF中,应用程序的基本组成包括窗口、控件、布局和样式等元素。通过这些组件,开发者可以...

    WPF深入浅出书上全部实例源码,非常详细

    本压缩包中的"深入浅出WPF_Example"包含了《WPF深入浅出》一书的所有实例源码,旨在帮助读者更好地理解和掌握WPF技术。这些实例覆盖了从基础概念到高级特性的各个方面,通过实际操作,让学习者能够深入理解WPF的各个...

    WPF源码WPF 源码WPF 源码WPF 源码WPF 源码WPF 源码

    WPF(Windows Presentation Foundation)是微软.NET框架的一部分,用于构建丰富的、交互式的桌面应用程序。它提供了强大的图形渲染能力,支持2D和3D图形、动画、媒体集成、数据绑定、样式和模板等特性,极大地提升了...

    wpf经典代码集合 wpf经典学习笔记 wpf从菜鸟到精通

    7. **事件处理**:WPF事件模型包括Routed Events和Attached Events,理解它们对于编写响应式UI至关重要。 8. **多媒体和图形**:WPF提供了强大的多媒体支持,包括图像、音频和视频,以及矢量图形和画布。 9. **文档...

    WpfApplication5_1

    在WPF中,事件处理机制尤为重要,尤其是路由事件(Routed Event)。本文将深入探讨WPF路由事件,以及如何在实际应用中使用。 **一、什么是路由事件** 路由事件(Routed Event)是WPF事件系统的核心特性,它允许...

    WPF自定义样式W:TabControlTest,倒计时,数字加减文本框,WPF圆形图像

    首先,**自定义样式(WPF Custom Style)**是WPF提供的一种强大机制,允许开发者为控件创建个性化的外观和行为。通过使用模板(ControlTemplate)和样式(Style),我们可以改变控件的视觉结构,甚至可以添加动画...

    WPF Movable and Resiable Panel Container Custom Control

    本主题将深入探讨“WPF Movable and Resizable Panel Container Custom Control”,这是一种专为在Canvas上实现移动(Move)和调整大小(Resize)功能而设计的自定义控件。这种控件允许用户自由地布局和调整UI元素的...

    WPF虚拟键盘输入

    在Windows Presentation Foundation(WPF)框架中,开发者有时需要为应用程序提供额外的安全保障,特别是涉及到用户输入敏感信息如密码时。这就是虚拟键盘的作用,它可以让用户通过鼠标点击屏幕上的按键来输入文字,...

    WPF Custom Visualization的第2部分:触发器

    在“WPF Custom Visualization的第2部分:触发器”这一主题中,我们将深入探讨如何利用触发器来实现动态的UI行为和视觉效果。触发器是一种强大的工具,它们可以改变元素的属性值或执行某些操作,当特定条件得到满足...

    WPF开发教程 ----WPF C# 编程 界面开发(很不错)

    WPF开发教程.rar 目录 WPF基础入门 3 1. WPF基础之体系结构 3 2. WPF基础之XAML 9 3. WPF基础之基元素 23 4. WPF基础之属性系统 26 5. WPF基础之路由事件 33 6. WPF基础之布局系统 46 7. WPF基础之样式设置和模板化...

    Multi Threading WPF Example

    A very useful multi-threading WPF example. If you want to build a multi-thread WPF application, then you must download it!

Global site tag (gtag.js) - Google Analytics