【发布时间】:2019-03-04 14:42:40
【问题描述】:
我要做的是:当文本框包含值“123”时,它应该启用按钮并允许我单击它。
我找不到根据我的 Button 参数触发 Button 命令(名为 SpecialCommand.cs 的类)的方法。你能支持我在哪里弄错了这个 MVVM 模式吗?
WPF 视图 [MainWindow.xaml]:
<Window.Resources>
<ViewModel:MainWindowVM x:Key="WindowVm"></ViewModel:MainWindowVM>
</Window.Resources>
<Grid>
<StackPanel>
<TextBox x:Name="textBox" Margin="0, 5" Text="123"/>
<Button Content="Click me!" Margin="0, 5" Command="{Binding SpecialCommand, Source={StaticResource WindowVm}}" CommandParameter="{Binding Text, ElementName=textBox, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</StackPanel>
</Grid>
ViewModel [MainWindowVM.cs]:
public class MainWindowVM
{
private SpecialCommand _specialCommand;
public SpecialCommand SpecialCommand { get => _specialCommand; set => _specialCommand = value; }
public MainWindowVM()
{
_specialCommand = new SpecialCommand();
}
}
命令 [SpecialCommand.cs]
public class SpecialCommand : ICommand
{
public bool CanExecute(object parameter)
{
if (parameter != null && (parameter as string) == "123")
return true;
return false;
}
public void Execute(object parameter)
{
MessageBox.Show("Button Pressed!");
}
public event EventHandler CanExecuteChanged;
}
我相信,也许这就是我弄错了,因为按钮和文本框在视图中,我不需要在我的 SpecialCommand 实现中添加/修改任何方法。他们应该能够看到属性何时更改。 就像下面的 CanExecuteChanged() 一样,这个命令会引发很多次,对于这个小任务来说似乎有点过分了。
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
【问题讨论】:
标签: c# wpf mvvm binding icommand