My problem is not wiring up DependencyProperties
in a UserControl
. This is not an issue. When I bind a button in a UserControl
to the UserControl
's DependencyProperty
called TargetCommand
, the binding breaks when I set a DataContext
on the UserControl
. I've tried using FindAncestor
and of course ElementName
, but they only function when there is no DataContext
on the UserControl
.
Is there a way around this?
example:
Main Window
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid>
<UserControls:MyUserControl
TargetCommand="{Binding PathToCommand}"
DataContext="{Binding PathToSomeModel}" />
MyUserControl Code Behind
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 RelativeSource and ElementName methods of binding in the MyUserControl both wire up correctly as long as the DataContext is not set on MyUserControl in the MainWindow. Neither work once the DataContext is set.
Is there a way to set a DataContext on MyUserControl, and still preserve the DependencyProperty Binding to TargetCommand?