How: Bind to a UserControl's DependencyProperty, when the UserControl has a DataContext?
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 t开发者_Go百科he 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?
Where is your PathToCommand
defined at? If I'm reading your example correctly, it should be somewhere higher in the VisualTree than the UserControl. In that case, you'd bind to whatever control has the DataContext containing PathToCommand and bind to DataContext.PathToCommand
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid x:Name="PART_Root">
<UserControls:MyUserControl
TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />
Not sure if I'm missing something here, but why do you need a DependencyProperty here when you are setting a DataContext? Why not have a property in your model that can be bound to directly from the button?
精彩评论