WPF之命令

WPF之命令

<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>
        <Button Height="100" Width="100" Content="命令测试" Command="{Binding Path=Test}" CommandParameter="{Binding User}"></Button>

        
        <!--没有事件函数会报错-->
        <Button Height="100" Width="100" Content="命令测试" Click="Button_Click"></Button>

        <!--可以先定义使用,后写-->
        <Button Height="100" Width="100" Content="命令测试" Command="{Binding Path=Test2}" CommandParameter="{Binding User2}"></Button>

    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace WpfApp1
{
    public class Context
    {
        /// <summary>
        /// 定义属性
        /// </summary>
        public ICommand Test { get; set; } = new TestCommand();

        public User User { get; set; } = new User();

    }

    /// <summary>
    /// 命令的定义(命令是类)
    /// </summary>
    public class TestCommand : ICommand
    {
        /// <summary>
        /// 状态变更通知事件
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// 判断是否执行
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="parameter"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Execute(object parameter)
        {

            User user = parameter as User;
            MessageBox.Show("测试"+ user.UserName);

        }
    }

    public class User
    {
        public string UserName { get; set; } = "111";
        public string PassWord { get; set; } = "222";
    }


}

在 WPF 中,命令(Command)是一种实现用户界面(UI)与应用程序逻辑分离的机制。通过使用命令,你可以将按钮点击、菜单项选择等用户操作与具体的业务逻辑解耦,从而提高代码的可维护性和可重用性


目的:用来取代事件函数
好处1:与具体的业务逻辑解耦
解耦了,就方便同时开展工作,进行分工合作
好处2:功能性更强:加上了是否执行的判定,还有状态变更通知,界面带参传递功能。

一 定义命令


    /// <summary>
    /// 命令的定义(命令是类)
    /// </summary>
    public class TestCommand : ICommand
    {
        /// <summary>
        /// 状态变更通知事件
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// 判断是否执行
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="parameter"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Execute(object parameter)
        {
            MessageBox.Show("测试");
        }
    }

二 使用命令

绑定数据上下文类

    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = new Context();
    }

绑定控件的命令属性

    <Grid>
        <Button Height="100" Width="100" Content="命令测试" Command="{Binding Path=Test}"></Button>
    </Grid>

三 命令传参

定义属性

    public class User
    {
        public string UserName { get; set; } = "111";
        public string PassWord { get; set; } = "222";
    }
    public class Context
    {
        /// <summary>
        /// 定义属性
        /// </summary>
        public ICommand Test { get; set; } = new TestCommand();

        public User User { get; set; } = new User();

    }
        <Button Height="100" Width="100" Content="命令测试" Command="{Binding Path=Test}" CommandParameter="{Binding User}"></Button>

在命令中使用

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="parameter"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Execute(object parameter)
        {

            User user = parameter as User;
            MessageBox.Show("测试"+ user.UserName);

        }

四 不用命令,用事件函数进行比较,说明什么是实现用户界面(UI)与应用程序逻辑分离解耦

  <!--没有事件函数会报错-->
  <Button Height="100" Width="100" Content="命令测试" Click="Button_Click"></Button>

  <!--可以先定义使用,后写-->
  <Button Height="100" Width="100" Content="命令测试" Command="{Binding Path=Test2}" CommandParameter="{Binding User2}"></Button>
<think>好的,我现在需要帮助用户了解WPF中Grid的使用教程和相关命令。首先,我得回忆一下用户提供的引用内容,引用1提到了WPF的基础知识,比如数据绑定、控件等,引用2是关于ComboBox的使用,可能和布局控件关系不大,但可以借鉴数据绑定的部分。用户明确询问Grid的教程和命令,所以重点应放在Grid的布局功能、行列表定义、附加属性以及可能的命令绑定。 首先,Grid是WPF中常用的布局容器,用于通过行列结构排列子元素。我需要详细说明如何定义行和列,使用RowDefinitions和ColumnDefinitions,以及如何设置子元素的位置,比如Grid.Row和Grid.Column附加属性。此外,合并单元格也是常见需求,可以通过RowSpan和ColumnSpan来实现。 然后,用户提到“命令”,可能是指输入命令或路由命令,但Grid本身更多是布局控件,可能没有内置命令,但可以通过事件处理或结合其他控件的命令来实现交互。例如,Grid可以处理鼠标事件,或者子控件可以使用命令绑定。需要澄清这一点,避免混淆。 接下来,我需要确保内容结构清晰,分步骤讲解Grid的基本用法、高级特性,并提供示例代码。同时,按照用户的要求,行内数学公式用$...$,独立公式用$$...$$,不过这里可能数学公式较少,更多的是XAML和C#代码。但要注意代码块的格式是否正确,比如使用三个反引号加语言类型。 然后,根据用户示例中的相关问题部分,我需要生成几个相关问题,例如Grid的布局优化、动态行列创建、数据绑定等。这些问题应该帮助用户进一步探索Grid的应用。 最后,检查是否引用了提供的参考资料。引用1提到数据绑定和基础知识,可以在讲解动态行列时引用。引用2关于ComboBox可能不太相关,但可以提及样式和模板的自定义,不过用户的问题主要是Grid,所以可能引用1更相关。 现在,整理思路,分步骤写出Grid的使用教程,包括基本结构、行列定义、附加属性、合并单元格、对齐方式、动态生成等。每个部分附上代码示例,并确保XAML语法正确。在动态生成部分,可以结合数据绑定,引用[^1]提到的数据绑定知识。最后列出相关问题,引导用户深入学习。</think>### WPF Grid 使用教程 #### 1. **基础布局结构** WPF 的 `Grid` 是用于创建行列布局的核心容器控件。通过定义行(`RowDefinitions`)和列(`ColumnDefinitions`),可以将子元素精确放置在网格中。例如: ```xml <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <!-- 自动适应内容高度 --> <RowDefinition Height="*"/> <!-- 占据剩余空间 --> <RowDefinition Height="2*"/> <!-- 按比例分配空间 --> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> </Grid> ``` #### 2. **子元素定位** 使用附加属性 `Grid.Row` 和 `Grid.Column` 设置子元素的位置(索引从0开始): ```xml <Button Grid.Row="0" Grid.Column="0" Content="按钮1"/> <TextBlock Grid.Row="1" Grid.Column="1" Text="文本块"/> ``` #### 3. **合并单元格** 通过 `Grid.RowSpan` 和 `Grid.ColumnSpan` 实现单元格合并: ```xml <Rectangle Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Fill="LightBlue"/> ``` #### 4. **对齐与边距** 设置子元素的水平和垂直对齐方式,并控制边距: ```xml <Button Grid.Row="2" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="10" Content="居中按钮"/> ``` #### 5. **动态生成行列** 通过代码动态添加行列(结合数据绑定知识[^1]): ```csharp // 添加新列 var newColumn = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }; myGrid.ColumnDefinitions.Add(newColumn); // 动态添加控件 var dynamicTextBlock = new TextBlock { Text = "动态内容" }; Grid.SetRow(dynamicTextBlock, 1); Grid.SetColumn(dynamicTextBlock, 2); myGrid.Children.Add(dynamicTextBlock); ``` #### 6. **Grid 常用命令与事件** - **命令绑定**:`Grid` 本身不直接支持命令,但可通过子控件(如按钮)绑定 `ICommand`。 - **事件处理**:支持鼠标、键盘等事件,例如 `MouseDown`: ```xml <Grid MouseDown="Grid_MouseDown"> ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值