将UserControl转换为自定义控件

下面的UserControl运行良好,但我想更容易更改样式。

我尝试过的一件事是将其转换为自定义控件,但我仍然坚持基础知识如何在处理属性更改的静态方法中设置ToolTip(参见下文)

另一件事我试图将Style转换为ResourceDictionary中的通用按钮样式,但这是这个问题的主题

如何在我的子类Button中设置ToolTip?

干杯

UserControl XAML:

    

UserControl代码背后:

 public partial class AddNewItemButton : UserControl { public AddNewItemButton() { InitializeComponent(); } public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register( "Subject", typeof (string), typeof (AddNewItemButton), new FrameworkPropertyMetadata(OnSubjectChanged)); public string Subject { get { return (string) GetValue(SubjectProperty); } set { SetValue(SubjectProperty, value); } } private static void OnSubjectChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var control = obj as AddNewItemButton; if (control == null) return; control._accesText.Text = "_" + string.Format(MasterDetail.Subject_AddNew_Label, control.Subject.Capitalize()); control._button.ToolTip = string.Format(MasterDetail.Subject_AddNew_ToolTip, control.Subject.ToLower()); } } 

尝试创建自定义控件失败:

 public class MyButton : Button { public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register( "ItemName", typeof(string), typeof(MyButton), new FrameworkPropertyMetadata(OnSubjectChanged)); public string Subject { get { return (string)GetValue(SubjectProperty); } set { SetValue(SubjectProperty, value); } } private static void OnSubjectChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var control = obj as MyButton; if (control == null) return; ToolTip = ??; } } 

UPDATE

根据菲尔的回答,控件(底部的)比我想象的更“不露面”: – )

结果

  public class AddNewItemButton : Button { static AddNewItemButton() { var type = typeof (AddNewItemButton); DefaultStyleKeyProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(type)); } #region Subject public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register( "Subject", typeof(string), typeof(AddNewItemButton), new PropertyMetadata(default(string))); public string Subject { get { return (string)GetValue(SubjectProperty); } set { SetValue(SubjectProperty, value); } } #endregion } 

Generic.xaml

                    

在此处输入图像描述

以下是带有工具提示的自定义按钮的示例(基于您最近提出的问题):

这是代码

 public class CustomButton : Button { static CustomButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton))); } public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register("Subject", typeof (string), typeof (CustomButton), new PropertyMetadata(default(string))); public string Subject { get { return (string) GetValue(SubjectProperty); } set { SetValue(SubjectProperty, value); } } } 

这在主题/ generic.xaml中

 Add new: