WPF命令绑定-无法找到与引用绑定的源

本文关键字:绑定 引用 命令 WPF | 更新日期: 2023-09-27 18:16:22

我尝试将视图中的按钮命令绑定到视图模型中的另一个类。然而,我得到以下错误:

System.Windows。数据错误: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>

WPF命令绑定-无法找到与引用绑定的源

Class1不位于按钮的可视树 ,因此不能使用RelativeSource绑定到它。

如果您已经将DataContext设置为Class1,那么您所需要的只是简单的绑定,绑定引擎将自动为您解析它。

<Button Height="50" Command="{Binding ClickCommand}"/>

如果你还没有设置DataContext,先这样设置:

<Window>
  <Window.DataContext>
     <local:Class1/>
  </Window.DataContext>
  <Grid> 
    <Button Height="50" Command="{Binding ClickCommand}"/>
  </Grid>
</Window>

如果您不想绑定DataContext,您必须将Class1实例声明为资源并访问它以绑定到命令。

<Window>
  <Window.Resources>
     <local:Class1 x:Key="class1"/>
  </Window.Resources>
  <Grid> 
    <Button Height="50"
            Command="{Binding ClickCommand, Source={StaticResource class1}}"/>
  </Grid>
</Window>