WPF命令绑定 - 找不到带引用的绑定源

时间:2014-08-03 14:37:19

标签: c# wpf xaml binding command

我试图将视图中按钮的命令绑定到视图模型中的另一个类。但是我收到以下错误:

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>

1 个答案:

答案 0 :(得分:1)

Class1不在于按钮 的Visual树中,因此无法使用 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>