WPF UserControl define Command and implemented in Window ViewModel

复制代码
//usercontrol
<UserControl x:Class="WpfApp154.ShowTextBtnUC"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp154"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button FontSize="100"
                Content="Show Text"
                Command="{Binding UCShowTxtCommand}"/>
        <TextBlock Grid.Row="1"
                   FontSize="100"
                   Foreground="Red"
                   Text="{Binding UCStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</UserControl>




//cs
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 WpfApp154
{
    /// <summary>
    /// Interaction logic for ShowTextBtnUC.xaml
    /// </summary>
    public partial class ShowTextBtnUC : UserControl
    {
        public ShowTextBtnUC()
        {
            InitializeComponent();
            this.DataContext = this;
        }



        public ICommand UCShowTxtCommand
        {
            get { return (ICommand)GetValue(UCShowTxtCommandProperty); }
            set { SetValue(UCShowTxtCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for UCShowTxtCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UCShowTxtCommandProperty =
            DependencyProperty.Register("UCShowTxtCommand", typeof(ICommand), 
                typeof(ShowTextBtnUC), new PropertyMetadata(null));




        public string UCStr
        {
            get { return (string)GetValue(UCStrProperty); }
            set { SetValue(UCStrProperty, value); }
        }

        // Using a DependencyProperty as the backing store for UCStr.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UCStrProperty =
            DependencyProperty.Register("UCStr", typeof(string), 
                typeof(ShowTextBtnUC), new PropertyMetadata(""));




    }
}




//MainWindow
<Window x:Class="WpfApp154.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"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp154"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:ShowTextBtnUC
            UCShowTxtCommand="{Binding DataContext.ShowTxtCommand,
            RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
            UCStr="{Binding DataContext.TbkStr,
            RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
    </Grid>
</Window>


using System.ComponentModel;
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;

namespace WpfApp154
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM();
            this.DataContext = vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        int idx = 0;

        public MainVM()
        {
            ShowTxtCommand = new DelCommand(ShowTxtCommandExecuted);
        }

        private void ShowTxtCommandExecuted(object? obj)
        {
            TbkStr = $"{++idx}\n\n{Guid.NewGuid().ToString("N")}";
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public ICommand ShowTxtCommand { get; set; }

        private string tbkStr="";
        public string TbkStr
        {
            get
            {
                return tbkStr;
            }
            set
            {
                if (value != tbkStr)
                {
                    tbkStr = value;
                    OnPropertyChanged(nameof(TbkStr));
                }
            }
        }
    }


    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        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);
        }
    }
}
复制代码

 

 

The key located at specificed assoicated implemented command of viewmodel via RelativeResource

 <local:ShowTextBtnUC
     UCShowTxtCommand="{Binding DataContext.ShowTxtCommand,
     RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
     UCStr="{Binding DataContext.TbkStr,
     RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   FredGrit  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2022-02-07 C++ Node template typename T
2022-02-07 In VSCode when input mi and press tab it will generate the MIT declaration automatically
2022-02-07 Loop through array via iterator
2022-02-07 C++ array random bubble sort
点击右上角即可分享
微信分享提示