RelativeSource-Binding for UserControl

前端 未结 1 1911
我在风中等你
我在风中等你 2021-01-15 14:29

I\'ve created a UserControl for displaying a Hyperlink in my application.

The markup of this UserControl looks like:



        
相关标签:
1条回答
  • 2021-01-15 15:09

    When you write

    <userControls:ActionLink LinkCommand="{Binding ViewCustomersCommand}"/>
    

    WPF tries to establish a data binding to a ViewCustomersCommand property in the DataContext of your UserControl, which is usually inherited from the control's parent, and holds a reference to some view model object. This doesn't work here because you have explicitly set the DataContext to the UserControl instance.

    As soon as you have bindable properties (i.e. dependency properties) in your UserControl, you should not set its DataContext. If you do so, you will always have to specifiy the binding source objects explicitly, because the DataContext is no longer inherited.

    So remove the

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    setting from your UserControl's XAML and set a RelativeSource in all its internal bindings:

    <Hyperlink
        Command="{Binding LinkCommand,
                  RelativeSource={RelativeSource AncestorType=UserControl}}"
        CommandParameter="{Binding LinkCommandParameter,
                           RelativeSource={RelativeSource AncestorType=UserControl}}">
        <TextBlock
            Text="{Binding LinkText,
                   RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Hyperlink>
    
    0 讨论(0)
提交回复
热议问题