【发布时间】:2014-08-03 14:37:19
【问题描述】:
我试图将视图中按钮的命令绑定到视图模型中的另一个类。但是我收到以下错误:
System.Windows.Data 错误:4:找不到参考绑定源
我的绑定有问题吗?如果有人可以提供帮助,我将不胜感激。非常感谢。
namespace WpfApplication1
{
public class Class1
{
public Class1()
{
_canExecute = true;
}
public void Print()
{
Console.WriteLine("Hi");
}
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute));
}
}
private bool _canExecute;
public void MyAction()
{
Print();
}
}
}
public class CommandHandler: ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged{
add{CommandManager.RequerySuggested+=value;}remove{CommandManager.RequerySuggested-=value;}
}
public void Execute(object parameter)
{
_action();
}
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Height="50" Command="{Binding ClickCommand, RelativeSource={RelativeSource AncestorType={x:Type local:Class1}}}"/>
</Grid>
</Window>
【问题讨论】:
标签: c# wpf xaml binding command