如何将ComboBoxItem的IsEnabled属性绑定到Command CanExecute方法的结果 [英] How to bind a ComboBoxItem's IsEnabled property to the result of a Command's CanExecute method

查看:137
本文介绍了如何将ComboBoxItem的IsEnabled属性绑定到Command CanExecute方法的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的SplitButton实现,其中包含一个ComboBox,其中包含几个绑定到命令的ComboBoxItem。我可以绑定到命名的名称,文本属性很好,但没有办法将ComboBoxItem的 IsEnabled 属性绑定到Command的 CanExecute 方法的结果,因为它是一个方法。有没有一些语法,我不知道绑定到方法,还是有一些诡计,将帮助我绑定到CanExecute。

I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's IsEnabled property to the result of a Command's CanExecute method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.

顺便说一句,考虑使用自定义ValueConverter除了我意识到,当CanExecute被重新评估时,我可能不会收到任何更新,因为它不是属性,因为我的命令不是业务对象。在我看来,我可能必须为命令创建一个ViewModel,以便仅在我自定义的SplitButton控件中使用,但这似乎有点笨重。

By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me.

推荐答案

ViewModel的另一个解决方案。下面是我如何使用ViewModel来解决我的问题。请注意,这个漂亮的NotifyPropertyChanged方法是我的基础ViewModel类的一部分。

Another solution by ViewModel. Below is how I used a ViewModel to solve my problem. And please note that the nifty NotifyPropertyChanged method is part of my base ViewModel class.

public class RoutedUICommandViewModel : ViewModel
{
    private RoutedUICommand _command;
    private IInputElement _target;

    public string Name { get { return _command.Name; } }

    public string Text { get { return _command.Text; } }

    public bool CanExecute
    {
        get
        {
            return _command.CanExecute(null, _target);
        }
    }

    public RoutedUICommand Command { get { return _command; } }

    public RoutedUICommandViewModel(ReportCommand command, IInputElement target)
    {
        _command = command;
        _target = target;
        _command.CanExecuteChanged += _command_CanExecuteChanged;
    }

    private void _command_CanExecuteChanged(object sender, EventArgs e)
    {
        base.NotifyPropertyChanged(() => this.CanExecute);
    }
}

这篇关于如何将ComboBoxItem的IsEnabled属性绑定到Command CanExecute方法的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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