最初我在代码后面有一个按钮事件。
private async void SomeCommand(object sender, RoutedEventArgs e)
{
MySlider.Value = MySlider.Value - 1;
在我的XAML中。
<Button Command="{Binding SomeCommand}">Do Something</Button>
现在我将使用MVVM。
public class MyViewModel : ViewModel
{
private readonly ICommand someCommand;
public MyViewModel()
{
this.someCommand = new DelegateCommand(this.DoSomething, this.CanDoSomething);
}
public ICommand SomeCommand
{
get { return this.someCommand; }
}
private void DoSomething(object state)
{
// do something here
}
private bool CanDoSomething(object state)
{
// return true/false here is enabled/disable button
}
}
我不知道方法DoSomething
中的代码是什么?
答案 0 :(得分:1)
如果要使用MVVM方法,则应使用可绑定的属性Value
。
你的xaml看起来像
<Slider x:Name="MySlider" Value="{Binding Value}" />
<Button Command="{Binding SomeCommand}">Do Something</Button>
在ICommand
中,您使用两个单独的方法来检查命令是否可以执行(CanDoSomething
)并执行它(DoSomething
)。
确保您的ViewModel实现INotifyPropertyChanged
,如果Value
发生更改,您必须提升public class MyViewModel : ViewModel
{
private readonly ICommand someCommand;
public MyViewModel()
{
this.someCommand = new DelegateCommand(this.DoSomething, this.CanDoSomething);
}
public ICommand SomeCommand
{
get { return this.someCommand; }
}
private void DoSomething(object state)
{
Value = Value - 1;
}
private bool CanDoSomething(object state)
{
//something like boundaries check of slider values and async is running and so on
}
private int _value;
public int Value
{
get { return _value; }
set
{
if (_value != value)
{
_value = value;
OnPropertyChanged(); //raise your propertyChanged event handler.
}
}
}
}
。您的ViewModel应该看起来像
{{1}}