在WPF中使用MVVM绑定命令

14

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

现在我想在MVVM中实现相同的功能。我阅读了很多文章,也看了许多sof上的答案,但仍然无法做到这一点。

请问有人可以给出一个简单的示例,其中一个按钮的click事件是在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框架?你尝试过什么? - D.Rosado
必须使用MVVM框架吗?我不知道任何框架。我唯一知道的是需要使用ICommand,但如何使用以及ViewModel需要做哪些更改,我不清楚。 - Narendra
2
不是必须的,但它非常有帮助,我推荐使用MVVM Light http://www.galasoft.ch/mvvm/ - D.Rosado
2个回答

28

您可以将按钮的Command属性绑定到任何返回ICommand的属性。 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中使用命令有一个非常相似的示例,其中包含可以轻松操作的代码。之前的Stack Overflow问题提供了一个示例,使用静态绑定到RoutedCommands:如何将关闭命令绑定到按钮,以及如何将WPF按钮绑定到ViewModelBase中的命令具有稍微更高级别的示例。


谢谢@slugster。DelegateCommand是系统定义的类还是我需要创建它?我正在检查您提供的链接。 - Narendra
@Narendra 这个已经在 Prism 库中定义好了,你只需要引用它们,或者查看 knock-off 版本的链接即可。 - slugster
我已经在问题中添加了最近的更改。您能否告诉我为什么它没有调用所需的函数? - Narendra
@Narendra 从我所看到的情况来看,您从未调用CreateSaveCommand(),因此SaveCommand的值将为null。 - slugster

5

看到很多答案都在实现这个ICommand接口,我建议一个更简单的选项,就是使用内置的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
}

现在开始对话。


这是一个非常好的答案。我已经点赞并在我的解决方案中使用了它,还进行了一些小改进,将按钮文本绑定到RoutedUICommand.Text属性上:<Button Command="{Binding ClearCommand}" Content="{Binding ClearCommand.Text}"/> - StefanoV
2
你的示例存在问题。在 ViewModel 类中,每次检索 Commands 属性时,都会向 commands 集合添加一个新的 ClearCommandCommandBinding。代码应该只在实例化时将 CommandBinding 添加到集合中一次。 - Tony Vitabile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接