WPF mvvm find element by name

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);
        }
    }
}

 

 

 

posted @ 2024-05-20 15:48  FredGrit  阅读(9)  评论(0编辑  收藏  举报