jpi*_*son 5 data-binding wpf xaml isenabled
我有一个自定义的 SplitButton 实现,其中包含一个 ComboBox,其中有多个绑定到命令的 ComboBoxItem。我可以很好地绑定到命令的 Name 和 Text 属性,但无法将 ComboBoxItem 的IsEnabled属性绑定到 Command 的CanExecute方法的结果,因为它是一个方法。是否有一些我不知道的用于绑定到方法的语法,或者是否有一些技巧可以帮助我绑定到 CanExecute。
顺便说一句,我考虑过使用自定义 ValueConverter,除了我意识到重新评估 CanExecute 时我可能不会收到任何更新,因为它不是属性,而且我的命令不是业务对象。在我看来,此时我可能必须为命令创建一个 ViewModel,以便仅在我的自定义 SplitButton 控件中使用,但这对我来说似乎有点过分了。
ViewModel 的另一个解决方案。下面是我如何使用 ViewModel 来解决我的问题。请注意,漂亮的 NotifyPropertyChanged 方法是我的 ViewModel 基类的一部分。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3495 次 |
| 最近记录: |