WPF自定义控件CustomControl中依赖属性、命令的使用

 Generic.xaml中的UI代码:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfCustomControlLibrary1">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <StackPanel Orientation="Horizontal"> 
                        <TextBlock x:Name="PART_ContentTextBox" Text="{TemplateBinding ContentMsg}"/>
                        <StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button  Margin="10"
                                         Grid.Column="0" Grid.Row="0"  Content="1" x:Name="PART_Button"/>
                                <Button   Command="local:CustomControl1.TestCommand" CommandParameter="1" Margin="10" Grid.Column="0" Grid.Row="1"   Content="2" x:Name="PART_Button2"/>
                                <Button   Command="local:CustomControl1.TestCommand" CommandParameter="2" Margin="10"  Grid.Column="0" Grid.Row="2"   Content="3" x:Name="PART_Button3"/> 
                            </StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button  Margin="10"  Grid.Column="1" Grid.Row="0"   Content="4" x:Name="PART_Button4"/>
                                <Button Margin="10"   Grid.Column="1" Grid.Row="1"   Content="5" x:Name="PART_Button5"/>
                                <Button Margin="10"   Grid.Column="1" Grid.Row="2"   Content="6" x:Name="PART_Button6"/>

                            </StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button   Margin="10" Grid.Column="2" Grid.Row="0"   Content="7" x:Name="PART_Button7"/>
                                <Button   Margin="10" Grid.Column="2" Grid.Row="1"   Content="8" x:Name="PART_Button8"/>
                                <Button  Margin="10"  Grid.Column="2" Grid.Row="2"   Content="9" x:Name="PART_Button9"/>

                            </StackPanel>
                        </StackPanel>
                      </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

后台代码中, 对Command进行声明和初始化以及寻找元素名, 然后在后台寻找此元素进行相应的操作

using System;
using System.Collections.Generic;
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 WpfCustomControlLibrary1
{
  
    [TemplatePart(Name = CustomControl1.ElementContentTextBox, Type = typeof(TextBlock))]
    public class CustomControl1 : Control
    {
        public CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
            ContentMsg = "Hello World"; 
        }
        private const string ElementContentTextBox = "PART_ContentTextBox";
        private const string Elementbutton = "PART_Button"; 
        Button button = null;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            button =  GetTemplateChild(Elementbutton) as Button;
            button.Click += Button_Click;
            CommandManager.RegisterClassCommandBinding(typeof(CustomControl1), new CommandBinding(TestCommand, TestExecute, TestCanExecute));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ContentMsg = "李四";
        }

      /// <summary>
      /// Registers a dependency property as backing store for the Content property
      /// </summary>
      public static readonly DependencyProperty ContentMsgProperty =
      DependencyProperty.Register("ContentMsg", typeof(object), typeof(CustomControl1),
      new FrameworkPropertyMetadata(null ));

        /// <summary>
        /// Gets or sets the Content.
        /// </summary>
        /// <value>The Content.</value>
        public object ContentMsg
        {
            get { return (object)GetValue(ContentMsgProperty); }
            set { SetValue(ContentMsgProperty, value); }
        }

        /// <summary>
        /// ICommand 属性
        /// </summary>
        public ICommand ContextMenuCommand
        {
            get { return (ICommand)GetValue(ContextMenuCommandProperty); }
            set { SetValue(ContextMenuCommandProperty, value); }
        }
        /// <summary>
        /// ICommand DependencyProperty
        /// </summary>
        public static readonly DependencyProperty ContextMenuCommandProperty =
            DependencyProperty.Register("ContextMenuCommand", typeof(ICommand), typeof(CustomControl1),
               new PropertyMetadata(null));

        public static readonly RoutedUICommand TestCommand =new RoutedUICommand("Test", "TestCommand", typeof(CustomControl1));
        private static void TestCanExecute(object sender, CanExecuteRoutedEventArgs e)
        { 
            e.CanExecute = true;
        }

        private void TestExecute(object sender, ExecutedRoutedEventArgs e)
        {
            CustomControl1 c = sender as CustomControl1;
            if (c == null) return;
            //你的计算逻辑
            ContentMsg = e.Parameter;
        }
    }
}

对于上面TemplatePartAttribute和Command.两种的使用方法分别是

1、    TemplatePartAttribute就是对UI中的元素命名, 然后在后台寻找此元素进行相应的操作(元素命名以”PART_“开始).此方法不建议使用,因为UI与逻辑耦合

2、建议使用Command,因为它能使UI和逻辑分离. 外部改写UI后, 只需对相应的元素重新绑定内置的Command就可以正常地工作

3、在项目中使用时

<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"
        xmlns:custom="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
        Title="MainWindow" Height="450" Width="800">
 
    <StackPanel>
        <custom:CustomControl1 ContentMsg="{Binding DateTimeMsg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  
                               x:Name="mycustom"  HorizontalAlignment="Left" Margin="55,30,0,0" VerticalAlignment="Top"></custom:CustomControl1>
        <Button Content="dsafsdf" Click="Button_Click" Height="40" Width="100" Margin="10"></Button>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
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 WpfCustomControlLibrary1;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MainViewModel mainViewModel = new MainViewModel();
        public MainWindow()
        {
            InitializeComponent();
           
            mainViewModel.DateTimeMsg = "张三";
            this.DataContext = mainViewModel;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(mainViewModel.DateTimeMsg.ToString());
        }
    }

     
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfCustomControlLibrary1
{
  
    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _DateTimeMsg;
        public string DateTimeMsg
        {
            get
            {
                return _DateTimeMsg;
            }
            set
            {
                _DateTimeMsg = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("DateTimeMsg"));
                }
            }
        }
        private string _ContentMsg;
        public string ContentMsg
        {
            get
            {
                return _ContentMsg;
            }
            set
            {
                _ContentMsg = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ContentMsg"));
                }
            }
        }
        
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WPF(Windows Presentation Foundation)是一个用于构建Windows应用程序的框架,而UserControlWPF的一种自定义控件。 UserControl允许我们将多个现有的WPF控件组合在一起,形成一个新的、可重用的控件。通过创建自定义的UserControl,我们可以将一组相关的控件封装成一个单一的控件,以增强应用程序的可维护性和重用性。 创建自定义的UserControl通常有以下几个步骤: 1. 创建一个新的WPF用户控件项目,并定义UserControl的外观和布局。这可以通过在XAML文件使用已有的WPF控件、布局容器和样式来完成。 2. 在UserControl的代码后台(Code-behind)文件,可以定义一些附加的属性和方法,以增强UserControl的可定制性和功能。 3. 在UserControl可以定义一些依赖属性(Dependency Properties),以允许开发者在使用UserControl时进行数据绑定和属性设置。 4. 在需要使用自定义UserControl的地方,可以将其直接添加到XAML,并进行相关的属性设置和事件处理。 自定义的UserControl可以在整个应用程序重复使用,从而提高了开发效率。通过UserControl的封装,我们可以将一组相关的功能和样式打包到单个控件,简化了应用程序的UI设计和代码开发过程。 总而言之,WPF自定义控件UserControl为开发者提供了一种简单且高效的方式来自定义和组合现有的WPF控件,以创建出更具可重用性和可维护性的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这个月太忙没时间看C++

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值