【发布时间】:2013-07-26 02:36:07
【问题描述】:
下面的代码是我的 WPF 应用程序的 MVVM 类。在我的 MainWindow.xaml.cs 文件 MainWindow() 构造函数中,我已经这样做了。
oneWayAuth = new OneWayAuthentication();
DataContext = oneWayAuth
我的主窗口包含多个按钮,我需要使用 ICommand 通过像这样的绑定来分配事件,
MainWindow.xaml
<Grid>
<Button> Command="{Binding ClickCommand}" Content="Button" Grid.Row="1" Name="button1" />
</Grid>
按钮的内部事件,我应该能够访问oneWayAuth.RandomNumber 属性,以便我可以更改它。
我尝试使用下面的方法。但我无法通过返回类型的 Action 委托。
OneWayAuthentication.cs
public class OneWayAuthentication : INotifyPropertyChanged
{
private string certData;
private string isVerifiedCert;
private string randomNumber;
private string response;
private string isVerifiedRes;
private string resultAuth;
public string RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
NotifyPropertyChanged("RandomNumber");
}
}
public ICommand ClickCommand
{
get
{
ICommand intfaceCmnd = new CommandHandler(() => Execute(), () => Switch());
return intfaceCmnd;
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Private Helpers
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
public bool Switch()
{
return true;
}
public void Execute()
{
this.RandomNumber = "this is random number";
}
}
CommandHandler.cs
public delegate bool delCanExecute(object parameter);
public class CommandHandler:ICommand
{
private Action _action;
private Action _canExecute;
public CommandHandler(Action action1, Action action2)
{
_action = action1;
_canExecute = action2;
}
public bool CanExecute(object parameter)
{
bool res = _canExecute();
return res;
}
public void Execute(object parameter)
{
_action();
}
public event EventHandler CanExecuteChanged;
}
【问题讨论】:
-
无法编译怎么办?试试 ICommand intfaceCmnd = new CommandHandler(Execute, Switch);。此外,每次调用 getter 时都会创建一个新的命令实例,我建议在构造函数中进行创建,并且仅在必要时进行更改。
-
行内
bool = _canExecute();不能在 CommandHandler.cs 中将类型“void”隐式转换为“bool” -
这是因为你的谓词是动作,它不能返回任何东西。命令处理程序(动作动作 1,动作动作 2)。 action2 分配给 CanExecute。改用谓词类型,msdn.microsoft.com/en-us/library/bfcke1bz.aspx
-
我还建议使用 MVVMLight 之类的 MVVM 框架,其中所有这些功能都已实现。