Mar*_*tin 7 mvvm relaycommand mvvm-light canexecute
我正在使用MVVM-Light,我的继电器命令工作正常,我刚刚读到我应该实现CanExecuteChanged
和CanExecute
.虽然我无法找到一个好的例子.
有没有人有一个如何实现这些的好例子.
CanExecute在无法执行时需要返回False,但不会只是取消按钮?
我什么时候执行CanExecuteChanged
?
任何人都有任何好的例子,什么时候使用每一个,我的代码工作没有,但这篇博文说明我应该实现这些项目.
我有点困惑,因为我说我认为我只是将Enabled
属性或东西绑定到ViewModel中的属性,所以我可以禁用按钮或类似的控件?
任何理解上的帮助都会非常感激.
编辑
这就是我现在所拥有的...它正在工作,但按钮不是物理禁用只有命令不运行,因为我返回false.我在构造函数中调用CanExecuteMe来强制运行RaiseCanExecuteChanged ...
这在我的viewmodel的construtor中运行
this.Page2Command = new RelayCommand(() => this.GoToPage2(), () => CanExecuteMe);
CanExecuteMe = false;
Run Code Online (Sandbox Code Playgroud)
这是我的其余代码,我从一个例子中得到了它.
private bool _canIncrement = true;
public bool CanExecuteMe
{
get
{
return _canIncrement;
}
set
{
if (_canIncrement == value)
{
return;
}
_canIncrement = value;
// Update bindings, no broadcast
//RaisePropertyChanged(CanIncrementPropertyName);
Page2Command.RaiseCanExecuteChanged();
}
}
public RelayCommand Page2Command
{
get;
private set;
}
private object GoToPage2()
{
System.Windows.MessageBox.Show("Navigate to Page 2!");
return null;
}
Run Code Online (Sandbox Code Playgroud)
这是我的XAML
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="31,77,0,0" x:Name="button1" VerticalAlignment="Top" Width="75" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Page2Command, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Run Code Online (Sandbox Code Playgroud)
小智 10
当Button需要确定是否应该启用CanExecute时,会调用CanExecute.
Button在绑定时执行此操作,并且每次触发CanExecuteChanged(Button都会为其命令侦听此事件).
因此,如果应该禁用该按钮,则应该触发CanExecuteChanged,当按钮调用CanExecute时,您应该返回false
.这是使用命令绑定时启用/禁用按钮的首选方法.
命令绑定使您能够封装实例(命令)中的所有按钮逻辑.CanExecute方法应查询应用程序的当前状态,以确定是应启用还是禁用该按钮.通过这种封装,您可以减少视图模型中的意大利面条代码,这些代码在这里和那里进行,然后在那里我忘了那个.
归档时间: |
|
查看次数: |
12379 次 |
最近记录: |