我已經嘗試了兩種不同的從ViewModel在WPF中進行命令的方法,並且不多。如果我把它放到視圖中,頂端方法很好,但我被告知這是不好的做法。我被告知的第二種方法是在MVVM中執行自定義命令的正確方法,但是我被困在如何實際調用/綁定來自View的命令。使用MVVM的自定義WPF命令的問題
視圖模型:
class MainViewModel : INotifyPropertyChanged
{
#region INPC
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
public readonly static RoutedUICommand myCommand;
static MainViewModel()
{
myCommand = new RoutedUICommand("customCommand","My Command",typeof(MainViewModel));
}
private void ExecutemyCommand(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("textBox1 cleared");
}
private void myCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}
在我查看的代碼我有這個,給了我一個錯誤
<Window x:Class="ConfigManager2.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:con="clr-namespace:ConfigManager2.Converters"
xmlns:vm="clr-namespace:ConfigManager2.ViewModel"
xmlns:local="clr-namespace:ConfigManager2.View"
.
.
.
<Window.CommandBindings>
<CommandBinding
Command="{x:Static vm:MainViewModel.myCommand}"
CanExecute="myCommandCanExecute"
Executed="ExecutemyCommand" />
</Window.CommandBindings>
.
.
.
<Button Content="COMMAND ME" Height="50px" Command="{x:Static vm:MainViewModel.myCommand}" />
我得到的錯誤是「ConfigManager2.View.MainView」不包含可以找到'ExecutemyCommand'的定義,並且沒有找到'ConfcuManager2.View.MainView'類型的第一個參數的擴展方法'ExecutemyCommand'可以找到(你是否缺少使用指令或程序集引用?)
我嘗試使用ICommand的另一種方法,結果被難倒就如何這個從XAML綁定到上述按鈕
視圖模型:
public ICommand ClearCommand { get; private set; }
public MainViewModel()
{
ClearCommand= new ClearCommand(this);
}
class ClearCommand : ICommand
{
private MainViewModel viewModel;
public ClearCommand(MainViewModel viewModel)
{
this.viewModel = viewModel;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
viewModel.vmTextBox1 = String.Empty;
MessageBox.Show("Textbox1 Cleared");
}
}
您的問題來自您的方法(ExecutemyCommand,myCommandCanExecute)是否是私有的(也是非靜態的)? – franssu
我不認爲這樣的錯誤甚至沒有看到視圖模型的原因我不知道。這就是說我把它們公之於衆,它仍然給我帶來同樣的錯誤。此外,我認爲這是從課堂上呼籲,但我不完全確定。 – Contristo