How: Bind to DependencyProperty UserControl when UserControl has a DataContext?

My problem is not wiring DependencyPropertiesin UserControl. It's not a problem. When I bind the button in UserControlto UserControl DependencyProperty, called TargetCommand, the binding breaks when I set DataContextto UserControl. I tried to use FindAncestorand, of course, ElementNamebut they only work when UserControlthere is nothing DataContext.

Is there any way around this?

Example:

Main window

<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
    <Grid>
         <UserControls:MyUserControl 
             TargetCommand="{Binding PathToCommand}"
             DataContext="{Binding PathToSomeModel}" />

MyUserControl code for

public partial class MyUserControl : UserControl
{
    public static readonly DependencyProperty TargetCommandProperty =
        DependencyProperty.Register( "TargetCommand", typeof( ICommand ), typeof( MyUserControl ) );

    public ICommand TargetCommand
    {
        get { return (ICommand)GetValue( TargetCommandProperty ); }
        set { SetValue( TargetCommandProperty, value ); }
    }

MyUserControl - Xaml

<UserControl x:Name="root">
    <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=TargetCommand}" />
    <Button Command="{Binding Path=TargetCommand, ElementName=root}" />

The binding methods of RelativeSource and ElementName in MyUserControl are both correctly connected until the DataContext is set to MyUserControl in MainWindow. None of them work after installing the DataContext.

DataContext MyUserControl - DependencyProperty TargetCommand?

+3
2

PathToCommand? , - VisualTree, UserControl. DataContext, PathToCommand, DataContext.PathToCommand

<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
    <Grid x:Name="PART_Root">
         <UserControls:MyUserControl 
             TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />
+3

, - , DependencyProperty , DataContext? , ?

0

Source: https://habr.com/ru/post/1792803/


All Articles