【问题标题】:Binding with ElementName in the nested UserControls在嵌套的 UserControls 中与 ElementName 绑定
【发布时间】:2010-12-27 16:08:38
【问题描述】:

我有以下简单代码:

<Window x:Class="WpfApplication3.MainWindow"
        x:Name="WindowInst" …>
        <local:UserControl1/>
</Window>
<UserControl x:Class="WpfApplication3.UserControl1" …>
    <Button Content="Click me"
        Command="{Binding DataContext.ButtonClickedCommand,
                        ElementName=WindowInst}" Height="134" Width="314" />
</UserControl>

在窗口的 ViewModel 中我有 ButtonClickedCommand:

#region Avatar click command
RelayCommand _buttonClickedCommand;
public ICommand ButtonClickedCommand
{
    get
    {
        if (_buttonClickedCommand == null)
        {
            _buttonClickedCommand = new RelayCommand(() => this.ButtonClicked());
        }
        return _buttonClickedCommand;
    }
}

public void ButtonClicked()
{
}
#endregion

不幸的是,它在运行时导致异常:

System.Windows.Data 错误:4:找不到引用“ElementName=WindowInst”的绑定源。 BindingExpression:Path=DataContext.ButtonClickedCommand;数据项=空;目标元素是 'Button' (Name='');目标属性是“Command”(输入“ICommand”)

你能解释一下它有什么问题吗?

【问题讨论】:

  • 你能显示你设置 DataContext 的位置吗?
  • 比如在窗口中DataContext="{Binding ViewModel, ElementName=WindowInst}"

标签: c# wpf binding


【解决方案1】:

尝试如下修改您的绑定...

<Window x:Class="WpfApplication3.MainWindow"
        x:Name="WindowInst" …>
        <local:UserControl1/>
</Window>
<UserControl x:Class="WpfApplication3.UserControl1" …>
    <Button Content="Click me"
        Command="{Binding Path=ButtonClickedCommand, Mode=FindAncestor, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Height="134" Width="314" />
</UserControl>

这应该可以工作,因为WindowInst 不在Self 中,因为您的容器是UserControl;它被放置在Window 中。此外,您需要确保将 DataContext 设置在 Window 内,否则其值为 null,无论您的语法是否准确,都不会发生绑定。

【讨论】:

  • 是的,我知道它会起作用。也许,我没有清楚地解释我的问题。我写了这段代码作为演示,实际上我在一个大型现实世界的应用程序中有更复杂的代码。所以我在这个现实世界的应用程序中没有窗口——我有 2 个用户控件 A 和 B。A 包含 B。A 可以很好地与我的绑定一样。 B 包含 A,所以我认为相同的绑定应该在 B 中工作,但它没有。
  • 哦,我明白了!我可以写RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}。谢谢。
【解决方案2】:

你的绑定有点不对劲。

请参阅this tutorial 了解 WPF 命令绑定。

作为一般规则,在绑定中指定的越少越好。我认为在这种情况下您不需要元素名称,并且 datacontext 是您绑定的假定根。

【讨论】:

  • CommandBindings 只能与代码后面的方法一起使用。就我使用 MVVM 而言,我没有任何代码,我所有的方法都在 ViewModel 中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
相关资源
最近更新 更多