首页 > 其他分享 >WPF mvvm find element by name

WPF mvvm find element by name

时间:2024-05-20 15:53:55浏览次数:19  
标签:name Windows System private find using WPF public DelCmd

Copy from https://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type

 

//xaml
<Window x:Class="WpfApp102.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:WpfApp102"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="50"/>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <TextBlock Text="{Binding DatetimeStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            <TextBlock Text="{Binding GuidStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            <Button Content="New Window" Command="{Binding NewWindowCmd}" FontSize="50" />
            <Button Content="Find Element" Command="{Binding FindEleCmd}" FontSize="50" />
            <TextBox x:Name="tbx" FontSize="30"/>
        </StackPanel>
    </Grid>
</Window>

 

//xaml.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 WpfApp102
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm=new MainVM();
            this.DataContext = vm;  
        }
    }
}

 

//mvvm
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApp102
{
    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            vmTimer = new System.Threading.Timer(VMTimerCallback,null,0,1000);             
        }

        private void VMTimerCallback(object state)
        {
            DatetimeStr = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            GuidStr = Guid.NewGuid().ToString();
        }

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

        private string datetimeStr = DateTime.Now.ToString("yyyyMMddHHmmssffff");
        public string DatetimeStr
        {
            get
            {
                return datetimeStr;
            }
            set
            {
                if(value!= datetimeStr)
                {
                    datetimeStr = value;
                    OnPropertyChanged(nameof(DatetimeStr));
                }
            }
        }

        private string guidStr=Guid.NewGuid().ToString();
        public string GuidStr
        {
            get
            {
                return guidStr;
            }
            set
            {
                if(value!=guidStr)
                {
                    guidStr = value;
                    OnPropertyChanged(nameof(GuidStr));
                }
            }
        }

        private System.Threading.Timer vmTimer { get; set; }

        private DelCmd findEleCmd;
        public DelCmd FindEleCmd
        {
            get
            {
                if(findEleCmd == null)
                {
                    findEleCmd = new DelCmd(FindEleCmdExecuted);
                }
                return findEleCmd;
            }
        }

        private void FindEleCmdExecuted(object obj)
        {
            TextBox foundTextBox =  Global.FindChild2<TextBox>(Application.Current.MainWindow, "NewWindowTbk");
            if(foundTextBox != null)            
            {
                foundTextBox.Text = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}";
            }
        }

        private DelCmd newWindowCmd;

        public DelCmd NewWindowCmd
        {
            get
            {
                if(newWindowCmd == null)
                {
                    newWindowCmd = new DelCmd(NewWindowCmdExecuted);
                }
                return newWindowCmd;
            }
        }

        private void NewWindowCmdExecuted(object obj)
        {
            Window win = new Window();
            TextBox tb = new TextBox();
            tb.Name = "NewWindowTbk";
            tb.Text = "Raw Content!";
            win.Content = tb;
            win.Show();
            win.Owner = Application.Current.MainWindow;
            var dc = win.DataContext;
            TextBox foundTextBox = Global.FindChild<TextBox>(win, "NewWindowTbk");
            if (foundTextBox != null)
            {
                foundTextBox.Text = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}";
            }
        }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged;
        protected void RaiseCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                handler?.Invoke(this, EventArgs.Empty);
            }
        }

        private Action<object> _execute;
        private Predicate<object> _canExecute;

        public DelCmd(Action<object> _executeValue, Predicate<object> _canExecuteValue)
        {
            _execute = _executeValue;
            _canExecute = _canExecuteValue;
        }

        public DelCmd(Action<object> _executeValue) : this(_executeValue, null)
        {
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}

 

 

 

标签:name,Windows,System,private,find,using,WPF,public,DelCmd
From: https://www.cnblogs.com/Fred1987/p/18202117

相关文章

  • 【C#】WPF字典资源设置Button控件样式
    <ResourceDictionaryxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Stylex:Key="BtnInfoStyle"TargetType="Button">......
  • net.sf.jsqlparser.schema.Column.withColumnName(Ljava/lang/String;)Lnet/sf/jsqlpar
    https://blog.csdn.net/yuanzhugen/article/details/133648431 SpringBoot整合mybatisplus报错:net.sf.jsqlparser.schema.Column,isavailablefromthefollowinglocationsAnattemptwasmadetocallthemethodnet.sf.jsqlparser.schema.Column.withColumnName(Ljava/l......
  • 自研WPF插件系统(沙箱运行及热插拔)
    前言插件化的需求主要源于对软件架构灵活性的追求,特别是在开发大型、复杂或需要不断更新的软件系统时,插件化可以提高软件系统的可扩展性、可定制性、隔离性、安全性、可维护性、模块化、易于升级和更新以及支持第三方开发等方面的能力,从而满足不断变化的业务需求和技术挑战。一......
  • x64 环境下_findnext() 函数报错——0xC0000005: 写入位置 0xFFFFFFFFDF47C5A0 时发生
    CSDN搬家失败,手动导出markdown后再导入博客园最近在搞单目相机位姿估计,相机标定参考了【OpenCV3学习笔记】相机标定函数calibrateCamera()使用详解(附相机标定程序和数据)提供的代码。/*@paramFile_Directory为文件夹目录@paramFileType为需要查找的文件类型@param......
  • Vue3报错:已声明“upperName”,但从未读取其值。ts-plugin(6133)
    Vue3报错:已声明“upperName”,但从未读取其值。ts-plugin(6133)报错显示:类型“StoreToRefs<Store<"count",{sum:number;name:string;address:string;},{},{increment(value:number):void;}>>”上不存在属性“upperName”。ts-plugin(2339)相关代码:vue文件:con......
  • find命令
    find帮助参数-aminN:最后一次访问文件的时间(以分钟计)与N相匹配。-anewerFILE:最后访问文件时间比指定文件FILE新的文件。-atimeN:最后一次访问文件的时间(以天为单位)与N相匹配。-cminN:最后一次更改文件的时间(以分钟计)与N相匹配。-cnewerFILE:最后更改文件......
  • 寻路算法 Pathfinding
    目录我该使用哪种算法?BreadthFirstSearch(BFS)Dijkstra’sAlgorithmGreedyBestFirstSearchA*Algorithm学UGUI的一般使用方法,然后在画grid,除了画热力图之外,还开始了解用于处理寻路的算法A*寻路算法是图搜索算法,所以我打算不用Unity自带的寻路组件,自己简单的实现一......
  • 01_WPF+Prism登录之PasswordBox的Binding
    #region登录信息///<summary>///密码///</summary>privatestring_Pwd;///<summary>///密码///</summary>publicstringPwd{get{return_Pwd;}......
  • WPF ListBox acts image container, ItemTemplate,DataTemplate,
    <Windowx:Class="WpfApp100.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • 不一样的WPF多语言切换方案
    前言作为技术而言,我并不认为多语言有什么值得深入研究的地方,本来也没打算开这个话题。前段时间看到了群里有朋友在讨论这个,一想到它确实也算一个比较常用的功能,所以决定对它做一个封装,如果您正好需要,希望对您有帮助。多语言切换一般有两种方案,一种是使用资源字典(xaml文......