几何尺寸与公差论坛

 找回密码
 注册
查看: 189|回复: 0

怎么使用commandbindings?

[复制链接]
发表于 2022-12-10 15:14:32 | 显示全部楼层 |阅读模式
如果要使用 CommandBindings 来绑定命令,可以使用以下步骤:

定义一个 CommandBinding 对象,并设置它的 Command 属性为要绑定的命令对象。
为 CommandBinding 指定一个事件处理程序,该事件处理程序将在命令被执行时被调用。
将 CommandBinding 添加到控件的 CommandBindings 集合中。
以下是一个简单的例子,展示了如何使用 CommandBindings 来绑定命令:

Copy code
<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.CommandBindings>
            <CommandBinding Command="{Binding MyCommand}"
                            Executed="OnMyCommandExecuted" />
        </Grid.CommandBindings>
        <Button Content="Click Me!"
                Command="{Binding MyCommand}" />
    </Grid>
</Window>
Copy code
using System.Windows;
using System.Windows.Input;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

        private void OnMyCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            // 执行命令的逻辑
        }
    }
}
在这个例子中,定义了一个 CommandBinding 对象,并将它添加到控件的 CommandBindings 集合中。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|几何尺寸与公差论坛

GMT+8, 2024-4-24 19:42 , Processed in 0.035040 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表