简体   繁体   中英

Button click event not rising in wpf

I have a wpf control, which contains many controls in its template.

I can find one of the elements from that template and subscribe to it's click event, but it's nor firing click event. why?

c# code

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

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

wpf code

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

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

Are you sure you are doing this in the right place. Whenever I have a control that needs access to its PARTS I do it in OnApplyTemplate like following :

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;
        ....
}

This is code that works. I notice here that I do this call in a specific method where I am sure that the control in question is initialised, and I am using a different method than you did to get to the part.

Check with a debugger that btn really has a value, or any of the parts for that matter because it is based on strings. Anyone can make a type so I usually verify this code by stepping through this with a debugger. Postpone this and you will have a difficult to find bug. If btn is null it is only logical that the event handler is not raised when you click the button.

The xaml for the WPF control that came with the example above is following :

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM