繁体   English   中英

在嵌套的UserControls中与ElementName绑定

[英]Binding with ElementName in the nested UserControls

我有以下简单的代码:

<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:路径= DataContext.ButtonClickedCommand; 的DataItem = NULL; 目标元素是'Button'(Name =''); 目标属性为“命令”(类型为“ ICommand”)

您能解释一下这是怎么回事吗?

尝试如下修改绑定...

<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 另外,您需要确保在Window中设置DataContext ,否则其值将为null并且无论语法是否正确,都不会发生绑定。

您的绑定有些不足。

请参阅有关WPF命令绑定的本教程

通常,在绑定中尽可能少地指定。 在这种情况下,我认为您不需要元素名称,并且datacontext是绑定的假定根。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM