【问题标题】:Button click event not rising in wpfwpf中的按钮单击事件没有上升
【发布时间】:2015-07-21 11:22:35
【问题描述】:

我有一个 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>

【问题讨论】:

  • 我猜btn 不为空?
  • 不明白为什么人们投票关闭。对我来说似乎是一个可行的问题。

标签: c# wpf events


【解决方案1】:

你确定你在正确的地方做这件事吗?每当我有一个需要访问其 PARTS 的控件时,我都会在 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 为 null,则单击按钮时不引发事件处理程序是合乎逻辑的。

上例附带的 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>

【讨论】:

  • 在您点击按钮之前,附加代码的事件处理程序是否已运行?
  • 它工作正常,当我只使用一个控制模板时
  • 您正在尝试制作自定义 WPF 控件吗?那么上面的方法就是这样做的方法。使用样式和设置器,其中为 targettype 设置了 controltemplate。
猜你喜欢
  • 2014-02-17
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多