使用MVVM在WPF中绑定命令

本文关键字:绑定 命令 WPF MVVM 使用 | 更新日期: 2023-09-27 18:11:42

我正在学习MVVMWPF。我有一个xaml文件在我的项目,它有一个简单的点击事件处理程序在后面的代码。

现在我想在MVVM中做同样的事情。我读了很多文章,也读了很多软件的答案。但仍然无法做到这一点。

谁能给一个简单的例子,其中一个按钮点击事件是在MVVM完成的。

编辑

<Window x:Class="WhiteBalance.BaseCalWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:uc="clr-namespace:NumberUpDownControl;assembly=NumberUpDownControl"
        xmlns:viewn="clr-namespace:WhiteBalance.ViewModels"
        Title="RefImgSettingWindow"  Height="900" Width="1000" ResizeMode="NoResize" 
        BorderThickness="4">
    <Window.Resources>
        <viewn:DashBoardViewModel x:Key="demokey"></viewn:DashBoardViewModel>
    </Window.Resources>
    <Grid x:Name="gdParent" DataContext="{StaticResource demokey}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="490" />
            <ColumnDefinition Width="488*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="300" />
            <RowDefinition Height="300" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0">
            <Label Content="{Binding Path=NAME,Mode=TwoWay}" Height="28" Name="lblTest" />
            <Button Content="Capture" Height="23" Name="btnCapture" Width="75" Command="{Binding Path=SaveCommand}"
                             Canvas.Left="94" Canvas.Top="254" />
        </StackPanel>
    </Grid>
</Window>
namespace WhiteBalance.ViewModels
{
    public class DashBoardViewModel: ObservableObject
    {
        private string _name = "dsqdasd";
        public string NAME
        {
            get { return _name; }
            set { _name = value; }
        }
        public ICommand SaveCommand
        {
            get;
            set;
        }
        private bool CanExecuteSaveCommand()
        {
            return true;    // !string.IsNullOrEmpty(LastName);
        }
        private void CreateSaveCommand()
        {
            SaveCommand = new RelayCommand(SaveExecute, CanExecuteSaveCommand);
        }
        public void SaveExecute()
        {
            //Person.Save(_newPerson);
            NAME = "Changed Name";
        }
        public DashBoardViewModel()
        {
            //objModel.TestText = "This will change";
            NAME = "TestName";
        }
    }
}

使用MVVM在WPF中绑定命令

您可以将按钮的Command属性绑定到返回iccommand的任何属性。Prism实现了一个非常方便的名为DelegateCommand的命令,它非常容易使用(这里是它的一个仿照):

public ICommand MyButtonClickCommand 
{
    get { return new DelegateCommand<object>(FuncToCall, FuncToEvaluate); }
}
private void FuncToCall(object context)
{
    //this is called when the button is clicked
}
private bool FuncToEvaluate(object context)
{
    //this is called to evaluate whether FuncToCall can be called
    //for example you can return true or false based on some validation logic
    return true;
}

<Button x:Name="myButton" Command="{Binding MyButtonClickCommand}" />

CodeProject示例如何在WPF中使用命令有一个非常相似的示例,您可以轻松地完成代码。以前的堆栈溢出问题有一个例子,使用RoutedCommands静态绑定到:如何绑定关闭命令到按钮,和如何绑定WPF按钮到ViewModelBase命令?有一个稍微高级一点的例子:

看到很多实现这个iccommand接口的答案,我建议使用一个更简单的选项,即使用内置的System.Windows.Input

下面是一个例子:

Xaml视图:

<Window
    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"
    x:Class="SomeDialog"
    SizeToContent="WidthAndHeight"
    WindowStartupLocation="CenterOwner" 
    ResizeMode="CanResizeWithGrip">
    <StackPanel>
        <Button Width="Auto" Command="{Binding ClearCommand}" Content="Clear"/>
    </StackPanel>
</Window>

查看后台代码:

using System.Windows;
public partial class SomeDialog : Window
{
    public SomeDialog()
    {
        var vm = new ViewModel();
        DataContext = vm;
        CommandBindings.AddRange(vm.Commands);
        InitializeComponent();
    }
 }

视图模型:

using System.Windows.Input;
public class ViewModel : ViewModelBase
{
    readonly CommandBindingCollection commands = new CommandBindingCollection();
    public static RoutedUICommand ClearCommand { get; set; } = new RoutedUICommand("Clear", "ClearCommand", typeof(ErrorDialog));
    public CommandBindingCollection Commands
    {
        get
        {
            commands.Add(new CommandBinding(ClearCommand, OnClearExecuted);
            return commands;
        }
    }
    void OnClearExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        view.DialogResult = true; //Indicate things
        view.Close(); //Close the window
    }
}

像这样调用:

public void OpenSomeDialog()
{
    var dialog = new SomeDialog() {Owner = Application.Current.MainWindow};
    bool? b = dialog.ShowDialog();
    if (b != null && (bool) b)
        //Do things
}

现在开始对话