英文:
WPF bind to changing command
问题
我有一个按钮,应该绑定到视图的命令。问题是这个命令会在运行时更改(最初为null)。我的代码如下:
MyViewModel.cs
public class MyViewModel : INotifyPropertChanged
{
// ...
private CommandStorage? _commandStorage;
public CommandStorage? commandStorage
{
get => _commandStorage;
set
{
_commandStorage == value;
OnPropertyChanged(nameof(CommandStorage));
}
}
public ICommand MyCommand => commandStorage?.MyStoredCommand;
// ...
}
MyView.xaml:
<Button Command="{Binding MyCommand}"
我面临的问题是,在初始化期间,MyCommand 会被设置为null一次。即使在commandStorage 更改后,MyCommand 也不会设置为新值。
英文:
I have a button that should bind to to command of a View. The problem is that this command changes runtime (and initially it is null). My code looks like this:
MyViewModel.cs
public class MyViewModel INotifyPropertChanged
{
....
private CommandStorage? _commandStorage;
public CommandStorage? commandStorage
{
get => _commandStorage;
set
{
_commandStorage == value;
OnPropertyChanged(nameof(CommandStorage));
}
}
public ICommand MyCommand => commandStorage?.MyStoredCommand;
......
}
MyView.xaml:
<Button Command={Binding MyCommand}
What I face here is that MyCommand is sets once to null during initialization. And even after commandStorage changes new value is not set to MyCommand.
答案1
得分: 1
绑定到您引发更改通知并移除多余的MyCommand
属性的CommandStorage
属性:
<Button Command="{Binding CommandStorage.MyStoredCommand}" />
当您为CommandStorage
属性引发PropertyChanged
事件时,绑定引擎无法知道要刷新MyCommand
属性的值。
另一种选择是在其他属性的setter中实际引发数据绑定属性的事件:
public CommandStorage? commandStorage
{
get => _commandStorage;
set
{
_commandStorage == value;
OnPropertyChanged(nameof(CommandStorage));
OnPropertyChanged(nameof(MyCommand));
}
}
我猜这只是一个拼写错误,但在您发布的代码中,该属性被称为commandStorage。
英文:
Bind to the CommandStorage
property that you raise change notifications for and remove the superfluous MyCommand
property:
<Button Command="{Binding CommandStorage.MyStoredCommand}" />
The binding engine cannot be supposed to know to refresh the value of the MyCommand
property when you raise the PropertyChanged
event for the CommandStorage
property.
The other option is to actually raise the event for the data-bound property in the setter of the other property:
public CommandStorage? commandStorage
{
get => _commandStorage;
set
{
_commandStorage == value;
OnPropertyChanged(nameof(CommandStorage));
OnPropertyChanged(nameof(MyCommand));
}
}
I guess it's just a typo but in the code you have posted, the property is called commandStorage.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论