WPF委托实现方法回调(刷新父窗体)

MainWindow.xaml(父窗体)

<StackPanel>
    <Label Content="{Binding Message}"/>
    <Button Content="Input User Name" Command="{Binding OpenSubWindowCommand}"/>
</StackPanel>

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();
    this.DataContext = new MainWindowViewModel();
}

MainWindowViewModel.cs

class MainWindowViewModel : INotifyPropertyChanged
{
    string message;

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string Message
    {
        get => message;
        set
        {
            message = value;
            OnPropertyChanged("Message");
        }
    }

    public ICommand OpenSubWindowCommand { get; set; }

    public MainWindowViewModel()
    {
        OpenSubWindowCommand = new CommandHandler(OpenSubWindow);
    }

    void OpenSubWindow()
    {
        SubWindow subWindow = new SubWindow((name) => { Message = $"hello {name}"; });
        subWindow.Show();
    }
}

SubWindow.xaml(子窗体)

<StackPanel>
    <TextBox Text="{Binding Name}"/>
    <Button Content="Send" Command="{Binding SendCommand}"/>
</StackPanel>

SubWindow.xaml.cs

public SubWindow(Action<string> callback)
{
    InitializeComponent();
    this.DataContext = new SubWindowViewModel(callback, this);
}

SubWindowViewModel.cs

class SubWindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    string name;
    public string Name
    {
        get => name;
        set
        {
            name = value;
            OnPropertyChanged("Name");
        }
    }

    Action<string> Callback { get; set; }
    SubWindow Window { get; set; }

    public SubWindowViewModel(Action<string> callback, SubWindow window)
    {
        SendCommand = new CommandHandler(Send);
        Callback = callback;
        Window = window;
    }

    public ICommand SendCommand { get; set; }

    void Send()
    {
        if (Callback != null)
        {
            Callback(name);
            Window.Close();
        }
    }
}
posted @ 2022-01-05 13:58  Kyle0418  阅读(779)  评论(0编辑  收藏  举报