一个人怎么"禁止"在WPF按钮使用MVVM模式?按钮、模式、个人、WPF

2023-09-07 02:10:15 作者:幸福化为乌有

我试图让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.

这两个答案帮助我极大。在肯特的帖子,他走了一步,解释为什么要实现你的应用程序的命令的基础设施,而不是禁止的方式,我曾问一个按钮:

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:

http://stackoverflow.com/questions/3476686/how-does-one-disable-a-button-in-wpf-using-the-mvvm-pattern/3476708#3476708

和答案给我原来的问题:

And the answer to my original question:

http://stackoverflow.com/questions/3476686/how-does-one-disable-a-button-in-wpf-using-the-mvvm-pattern/3476697#3476697

推荐答案

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

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:

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

阅读这个帖子以了解更多关于 DelegateCommand

 
精彩推荐
图片推荐