簡體   English   中英

是否可以在WPF模板控件中公開新事件/屬性?

[英]It's possible to expose new events/properties in a WPF templated control?

也許最明顯的答案是我需要使用UserControl,但我想知道是否可行。

我想自定義ComboBox以顯示其他按鈕。 我已經能夠創建一個模板,該模板呈現內置下拉按鈕旁邊的按鈕。 現在,如何連接Click事件或訪問其任何屬性(例如IsEnabled)。

您不需要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;
        }
    }

}

有時可以使用附加的屬性/事件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM