2011-02-17 83 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

相關問題