如何“禁用"使用 MVVM 模式的 WPF 中的按钮? [英] How does one "disable" a button in WPF using the MVVM pattern?

查看:53
本文介绍了如何“禁用"使用 MVVM 模式的 WPF 中的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试掌握 WPF 和 MVVM,并且取得了良好的进展.WPF 和 MVVM 方面进展顺利.

I'm trying to get a grasp on WPF and MVVM and have been making good progress. The WPF and MVVM side of things are going well.

然而,XAML 和数据绑定方面是另一回事:)

However, the XAML and data binding side is a whole other story :)

我将如何禁用"按钮?

例如,我的视图模型中有一个 CanClose 属性,用于确定当前是否可以关闭应用程序.如果工作线程停止执行某事,则此属性设置为 false,我想将按钮灰显或以某种方式通过某种绑定在视觉上禁用关闭"按钮.

For example, I have a CanClose property in my view model that determines whether or not the application can currently be closed. If a worker thread is off doing something, then this property is set to false and I'd like to either grey out the button or somehow visually disable the Close button via some sort of binding.

我该怎么做?

谢谢!

编辑 -

可惜我只能接受一个答案.

Too bad I can only accept one answer.

这两个答案对我帮助很大.在 Kent 的帖子中,他更进一步解释了为什么应该在应用程序中实现命令基础结构,而不是像我问的那样禁用按钮:

These two answers helped me tremendously. In Kent's post, he went a step further by explaining why you should implement a command infrastructure in your application instead of disabling a button in the way that I had asked:

如何是否禁用"使用 MVVM 模式的 WPF 中的按钮?

以及我原来问题的答案:

And the answer to my original question:

如何是否禁用"使用 MVVM 模式的 WPF 中的按钮?

推荐答案

通过使用命令模式的方式.在您的视图模型中:

By way of using the command pattern. In your view model:

public class MyViewModel : ViewModel
{
    private readonly ICommand someCommand;

    public MyViewModel()
    {
        this.someCommand = new DelegateCommand(this.DoSomething, this.CanDoSomething);
    }

    public ICommand SomeCommand
    {
        get { return this.someCommand; }
    }

    private void DoSomething(object state)
    {
        // do something here
    }

    private bool CanDoSomething(object state)
    {
        // return true/false here is enabled/disable button
    }
}

在您的 XAML 中:

In your XAML:

<Button Command="{Binding SomeCommand}">Do Something</Button>

阅读 这篇文章 以了解有关 DelegateCommand 的更多信息.

Read this post to find out more about the DelegateCommand.

这篇关于如何“禁用"使用 MVVM 模式的 WPF 中的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆