我有一个视图(X.Xaml),它有一些控件,包括一个CheckBox.
当我检查CheckBox它时应该使会话成为True并且当我取消选中它时,它必须使会话False.
如果我在X.Xaml.cs代码隐藏中执行它,那将很容易但我希望我的代码干净.
无论如何使用Command并在ViewModel端处理它?
为什么不能简单地在IsChecked-Property上创建一个ViewWodel-Property的TwoWay-Binding并对该属性进行更改?
在viewModel中:
private bool _IsSessionEnabled;
public bool IsSessionEnabled
{
get { return _IsSessionEnabled; }
set {
if (_IsSessionEnabled != value) {
_IsSessionEnabled = value;
this.OnPropertyChanged();
this.switchSession(value); /* this is your session code */
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在视图中:
<CheckBox IsChecked={Binding IsSessionEnabled, Mode=TwoWay}
Content="Session active" />
Run Code Online (Sandbox Code Playgroud)
在提升事件之前(或之后,如你所愿)回应你自己的OnPropertyChanged实现中的Property Change会更加清晰.
回答你的问题:是的,有.
你必须创建Command类实现ICommand:
public class MyCommand : ICommand
{
Action<bool> _action;
public MyCommand(Action<bool> action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event System.EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action((bool)parameter);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的ViewModel中创建命令本身:
private MyCommand simpleCommand;
public MyCommand SimpleCommand
{
get { return simpleCommand; }
set { simpleCommand = value; }
}
public MainViewModel()
{
SimpleCommand = new MyCommand(new Action<bool>(DoSomething));
}
public void DoSomething(bool isChecked)
{
//something
}
Run Code Online (Sandbox Code Playgroud)
并将你的Checkbox命令绑定到它,以及CommandParametertoCheckbox.IsChecked
<CheckBox Name="checkBox1" Command="{Binding Path=SimpleCommand}" CommandParameter="{Binding ElementName=checkBox1, Path=IsChecked}" />
Run Code Online (Sandbox Code Playgroud)
但这有点夸张.您可能最好bool在ViewModel中创建相应的属性,绑定到它并在访问器中调用所需的代码.
| 归档时间: |
|
| 查看次数: |
6353 次 |
| 最近记录: |