简体   繁体   中英

Binding with ElementName in the nested UserControls

I have the following simple code:

<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>

And in the ViewModel for the Window I have 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

Unfortunately, it causes exception at runtime:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=WindowInst'. BindingExpression:Path=DataContext.ButtonClickedCommand; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

Could you explain me what's wrong with it?

Try modifying your binding as follows...

<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>

This should work as WindowInst does not live within Self since your container is the UserControl ; which is being placed within the Window . In addition you need to make sure that you are setting your DataContext within the Window or its value will be null and no binding will ever occur no matter if your syntax is accurate or not.

Your bindings are a little off.

Please see this tutorial on WPF command binding.

As a general rule, specify as little as possible in your bindings. I don't think you need element name in this circumstance and datacontext is the assumed root of your bindings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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