2011-10-31 72 views
4

我試圖傳遞一個命令到WPF用戶控件中的一個元素。無法傳遞/綁定到WPF用戶控件的命令

<UserControl x:Class="MyApp.MyControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <!-- shortened --> 
    <Button Command="{Binding Command}"> 
     <Button.Content> 
      <!-- shortened --> 
     </Button.Content> 
    </Button> 
</UserControl> 
public partial class MyControl : UserControl 
{ 
    public static readonly DependencyProperty CommandProperty 
     = DependencyProperty.Register("Command", 
              typeof(ICommand), typeof(MyControl)); 
    //shortened   
    public ICommand Command 
    { 
     get { return (ICommand)GetValue(CommandProperty); } 
     set { SetValue(CommandProperty, value); } 
    } 
    //shortened 
} 
<uc:MyControl Command="{Binding DoStuffCommand}" /> <!-- shortened --> 

當用戶控制按鈕被點擊時,沒有任何反應。
當我調試時,Command屬性爲空。
將命令綁定到用戶控件外部的按鈕確實有效。
這裏怎麼回事?

回答

5

名稱的控制和使用ElementName

<UserControl ... 
      Name="control"> 
    <Button Command="{Binding Command, ElementName=control}"> 
    <!-- ... --> 
+0

請查看Rachel的崗位 – David

0

嘛,我只想綁定到由主機控制/窗口的命令。因爲數據上下文將從它繼承。像這樣的東西。

<UserControl x:Class="MyApp.MyControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <!-- shortened --> 
    <Button Command="{Binding DoStuffCommand}"> 
     <Button.Content> 
      <!-- shortened --> 
     </Button.Content> 
    </Button> 
</UserControl> 

然後,您可以從代碼隱藏文件中刪除依賴項屬性代碼。

,並刪除命令屬性綁定,

<uc:MyControl /> 
+0

壞主意的答覆,因爲用戶控件可能不一定有'DoStuffCommand'在它的DataContext – Rachel

+0

顯然,如果財產是不是有這是行不通的數據上下文。但是,我不同意這是一個壞主意。你需要更多的信息來確定它是否是一個壞主意。我只是想爲問題提供解決方案。 – Brad

+1

我想這不是一個問題,如果你希望這個'UserControl'始終與特定的'ViewModel'一起使用,但是我覺得這是一個壞主意,如果這個UserControl是控制庫的一部分 – Rachel

8

默認DataContextButton是你的用戶控件的DataContext,不是你的用戶控件,所以你試圖綁定到的DataContext.Command代替UserControl.Command

要綁定到UserControl.Command,使用RelativeSource綁定

<Button Command="{Binding Command, RelativeSource={ 
     RelativeSource AncestorType={x:Type local:MyControl}}}"> 

編輯只要注意HB's answer,這也將工作。通常我喜歡RelativeSource綁定ElementName的人,因爲有時我重命名的項目,並用於忘記名稱

+0

我忘了提及**用戶控件構造函數**如下所示: 'code' public MyControl() { InitializeComponent(); DataContext = this; } '代碼' 另一個綁定元素,一個字符串字段工作得很好,這是不起作用的命令。 我在模擬一些東西嗎? – David

+0

另外,正如我所提到的,用戶控件**中的** Command屬性在調試時爲** null **。該命令確實存在並將其綁定到一個按鈕上,而不是用戶控件確實起作用。 – David

+0

@David如果你在我的回答中使用了'RelativeSource'綁定,而不是你在問題中的簡單綁定,那麼命令是否正常工作? – Rachel

0

什麼其他控件引用該項目在一般情況下,我公司始終遵循瑞秋意見(像上面one)。但在這種特殊情況下,我會考慮在用戶控件的根元素上設置DataContext,然後在那裏做一個整潔的綁定。

<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, 
          AncestorType={x:Type UserControl}}}"> 
<!-- shortened --> 
    <Button Command="{Binding Command}"> 
     <Button.Content> 
      <!-- shortened --> 
     </Button.Content> 
    </Button> 
</Grid >