可以在WPF模板化控件中公开新事件/属性吗?

时间:2009-12-10 08:47:57

标签: wpf events templates properties wpf-controls

也许明显的答案是我需要使用UserControl,但我想知道这是否可行。

我想自定义一个ComboBox来显示一个额外的按钮。我已经能够创建一个模板,用于呈现内置下拉按钮旁边的按钮。现在,我如何连接Click事件或访问其任何属性(例如IsEnabled)。

2 个答案:

答案 0 :(得分:1)

您不需要UserControl,但您必须从ComboBox继承以扩展它。你会写这样的东西:

[TemplatePart(Name = "PART_ExtraButton", Type = typeof(Button))]
public class ExtendedComboBox: ComboBox {

    private Button extraButton = new Button();
    public Button ExtraButton { get { return extraButton; } private set { extraButton = value; } }

    public static readonly RoutedEvent ExtraButtonClickEvent = EventManager.RegisterRoutedEvent("ExtraButtonClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ExtendedComboBox));

    public event RoutedEventHandler ExtraButtonClick {
        add { AddHandler(ExtraButtonClickEvent, value); }
        remove { RemoveHandler(ExtraButtonClickEvent, value); }
    }

    void OnExtraButtonClick(object sender, RoutedEventArgs e) {
        RaiseEvent(new RoutedEventArgs(ExtraButtonClickEvent, this));
    }

    public bool IsExtraButtonEnabled {
        get { return (bool)GetValue(IsExtraButtonEnabledProperty); }
        set { SetValue(IsExtraButtonEnabledProperty, value); }
    }

    public static readonly DependencyProperty IsExtraButtonEnabledProperty =
        DependencyProperty.Register("IsExtraButtonEnabled", typeof(bool), typeof(ExtendedComboBox), new UIPropertyMetadata(OnIsExtraButtonEnabledChanged));

    private static void OnIsExtraButtonEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        ExtendedComboBox combo = (ExtendedComboBox)d;
        combo.ExtraButton.IsEnabled = (bool)e.NewValue;
    }

    public override void OnApplyTemplate() {
        base.OnApplyTemplate();
        var templateButton = Template.FindName("PART_ExtraButton", this) as Button;
        if(templateButton != null) {
            extraButton.Click -= OnExtraButtonClick;
            extraButton = templateButton;
            extraButton.Click += new RoutedEventHandler(OnExtraButtonClick);
            extraButton.IsEnabled = this.IsExtraButtonEnabled;
        }
    }

}

答案 1 :(得分:0)

有时可能使用附加属性/事件