2011-02-17 81 views
3

我的问题是没有连线DependencyPropertiesUserControl。这不是问题。当我将UserControl中的按钮绑定到UserControlDependencyProperty时,调用TargetCommand,当我在UserControl上设置DataContext时,绑定中断。我尝试过使用FindAncestor,当然还有ElementName,但它们仅在UserControl上没有DataContext时起作用。如何:当UserControl具有DataContext时绑定到UserControl的DependencyProperty?

有没有办法解决这个问题?

例如:

主窗口

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

的MyUserControl代码后面

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}" /> 

的的RelativeSource和方法具的ElementName只要未在MainWindow中的MyUserControl上设置DataContext,MyUserControl中绑定的ds都会正确连接。一旦设置了DataContext,就不会工作。

有没有办法在MyUserControl上设置DataContext,并仍然将DependencyProperty绑定到TargetCommand?

回答

3

您的PathToCommand在哪里定义?如果我正确地阅读你的例子,它应该在VisualTree比UserControl更高的地方。在这种情况下,你会绑定到任何控件包含PathToCommand在DataContext并绑定到DataContext.PathToCommand

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

不错......我忽略了这一点。谢谢 – Nicholas 2011-02-17 19:42:20

0

不确定是否在这里丢失了某些东西,但是为什么在设置DataContext时需要一个DependencyProperty?为什么不在你的模型中有一个可以直接从按钮绑定的属性?

+0

它只是没有意义的,这个命令连接到我的模型。从我的模型角度来看。 – Nicholas 2011-02-17 14:42:28

相关问题