2015-07-21 143 views
1

我有一個wpf控件,其中包含模板中的許多控件。按鈕點擊事件不上升wpf

我可以從該模板中找到其中一個元素並訂閱它的單擊事件,但它也沒有觸發單擊事件。爲什麼?

C#代碼

var btn = element.FindChild<ToggleButton>("PART_ExpandToggleButton"); 
if (btn != null) btn .Click += Clicked; 

private void Clicked(object sender, RoutedEventArgs e) 
{ 
    //do some code 
} 

WPF代碼

<ControlTemplate x:Key="MainDataTemplate"> 
    <Control Template="{DynamicResource ConnectorTemplate}" /> 
</ControlTemplate> 

<ControlTemplate x:Key="ConnectorTemplate"> 
    <ToggleButton x:Name="PART_ExpandToggleButton" /> 
</ControlTemplate> 
+3

我猜'btn'不爲空? –

+0

是的,btn不爲空 –

+3

不明白爲什麼人們投票結束。對我來說似乎是一個可行的問題。 –

回答

0

你確定你是在正確的地方這樣做。每當我有一個需要它的零件我做在OnApplyTemplate像下面的訪問控制:

public override void OnApplyTemplate() 
{ 
     base.OnApplyTemplate(); 
     VisualStateManager.GoToState(this, "Normal", false); 

     //get the different parts 
     clearFilterPart = this.GetTemplateChild("ClearFilterPart") as Button; 
     distinctFilterPart = this.GetTemplateChild("DistinctFilterPart") as ToggleButton; 
     .... 
} 

這是工作的代碼。我在這裏注意到,我在一個特定的方法中進行了這個調用,我確信所討論的控件是初始化的,而且我正在使用與您不同的方法來獲取該部分。

用一個調試器檢查btn是否真的有一個值,或者是因爲它是基於字符串的任何部件。任何人都可以創建一個類型,所以我通常使用調試器來驗證這些代碼。推遲這個,你會很難找到錯誤。如果btn爲空,則只有當您單擊該按鈕時纔會引發事件處理程序。

的WPF控件與上面的例子中附帶的XAML是以下幾點:

<Style TargetType="{x:Type local:FilterTextBox}"> 
    <Setter Property="IsTabStop" Value="False"/> 
    <Setter Property="Background" Value="White"/> 
    <Setter Property="Focusable" Value="True"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:FilterTextBox}"> 
       ... 
       <Button x:Name="ClearFilterPart" /> 
       ... 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

btn不爲空。 –

+0

並且在單擊按鈕之前運行事件處理程序附加代碼? –

+0

是的,它跑了。 –