简体   繁体   English

WPF UI无法更新

[英]Wpf UI does not update

I have a wpf mvvm application. 我有一个wpf mvvm应用程序。 There is a button in the view and it is bound to a command in the view model. 视图中有一个按钮,该按钮绑定到视图模型中的命令。 The function CanExecute of this command returns the value of some bool property 此命令的CanExecute函数返回某些bool属性的值

private bool Command1CanExecute()
{
    return IsConnected;
}

When the property is changed, the button should become disabled but it's doesn't happened until I click somewhere in UI. 更改属性后,该按钮应被禁用,但是直到我单击UI中的某个位置时,按钮才会禁用。 The solution I have thought about (and it works :) ) is to run 我考虑过的解决方案(它可以工作:))是运行

  CommandManager.InvalidateRequerySuggested();

each second (Dispatcher timer can do it). 每秒(分派器计时器可以做到)。

Is there another, more elegant solution for my problem? 对于我的问题,还有其他更优雅的解决方案吗? Thank you. 谢谢。

Matvey. 马特维。

All Commands are updated after any userinteraction. 任何用户交互后,所有命令都会更新。 If you change a property programmatically and want to update the command-states you have to suggest a requery after your property has changed: 如果您以编程方式更改属性并想更新命令状态,则必须在属性更改后建议重新查询:

CommandManager.InvalidateRequerySuggested();

you can also raise a CanExecuteChanged-Event of your command (which simply does nothing else than above) 您还可以引发命令的CanExecuteChanged-Event(仅执行上述操作)

Command1.RaiseCanExecuteChanged();

you'd insert any of this in the setter of IsConnected like following 您可以将以下任何内容插入IsConnected的设置器中,如下所示

private bool _isConnected;
public bool IsConnected
{
  get { return _isConnected; }
  set
  {
    if (_isConnected != value)
    { 
      _isConnected = value;
      RaisePropertyChanged(); //or something similar
      Command1.RaiseCanExecuteChanged();
    }
  }
}

if you don't want that, you can just return true in your CanExecute-Handler and bind IsEnabled of your button to the property itself. 如果您不希望这样做,则可以在CanExecute-Handler中返回true并将按钮的IsEnabled绑定到属性本身。

<Button IsEnabled="{Binding IsConnected}" Command="{Binding Command1}" ... />

For those who uses MicroMvvm the change needs to be applied to the class: public class RelayCommand<T>:ICommand 对于使用MicroMvvm的用户,需要将更改应用于以下类: public class RelayCommand<T>:ICommand

and method: 和方法:

 [DebuggerStepThrough]
        public Boolean CanExecute(Object parameter)
        {

            var valu = _canExecute == null ? true : _canExecute();
            CommandManager.InvalidateRequerySuggested();
            return valu;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM