【问题标题】:Is there a best way to manually disable and re-enable a binded button?是否有手动禁用和重新启用绑定按钮的最佳方法?
【发布时间】:2013-05-13 12:04:42
【问题描述】:

在我的 ViewModel 中,我有以下方法:

public async Task<Boolean> DoSomething(Button sender)
{
    Binding binding = sender.GetBindingExpression(Button.IsEnabledProperty).ParentBinding;

    sender.IsEnabled = false;

    DoFastStuffs();

    await Task.Delay(250);

    sender.SetBinding(Button.IsEnabledProperty, binding);

    return true;
}

有没有更好的方法来做到这一点?因为我注意到手动设置属性而不将绑定保存在某处会永远从 XAML 对象中删除实际绑定。

编辑:这是我的按钮:

<Button IsEnabled="{Binding Converter={StaticResource ObjectToBooleanConverter}, ElementName=ComboBox, Path=SelectedItem}"/>

【问题讨论】:

  • 如果您有一个属性 (Button.IsEnabled) 绑定到源属性(大概在您的 VM 上),那么您为什么不直接更改源属性呢?如果您已将按钮绑定到ICommand,那么您将更改CanExecute 的返回值并提高CanExecuteChanged
  • 在虚拟机中操作绑定(几乎)总是错误的方式。
  • 问题是 IsEnabled 属性绑定到 ComboBox 的 SelectedItem。然后没有选择任何项目,按钮被禁用,反之亦然。我真的应该创建一个 Multiconverter 和另一个通知属性来临时禁用按钮吗?
  • 您的Button 是否绑定到Command?如果是这样,正确的方法可能是使用命令的CanExecute() 返回false,如果SelectedItemnull 或者IsLoading=true
  • 根据 MVVM 的视图模型不包含对视图的引用(在您的情况下为按钮) - 所以请不要将其称为 ViewModel。对于您的问题,请检查使用 MVVM(RelayCommand 或 DelegateCommand)进行指挥

标签: c# .net wpf xaml data-binding


【解决方案1】:

为什么不绑定按钮的 Command 属性。实现 ICommand 还将为您提供(几乎)免费的 UI 控件上的启用/禁用操作,使用 CanExecute() 功能来检查您的 ComboBox 的选定项...

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-09-20
  • 2016-04-13
  • 1970-01-01
  • 2013-06-24
  • 2014-09-27
  • 2011-05-10
  • 2017-07-16
  • 2010-09-17
相关资源
最近更新 更多