声明自定义控件

本文关键字:自定义控件 声明 | 更新日期: 2023-09-27 18:36:11

我将使用一堆控件,每个控件都由一个标签和一个文本框组成。声明自定义控件以便将标签的标题和文本框的输入区域封装为一个,是否是一个好主意?

我可能可以在 C# 中继承和创建一些东西,但这里的重点是在 XAML 方面做得更好,因此通过标记声明这种东西(不确定它是否称为资源、模板、样式或其他任何东西)是首选(如果还没有必要)。

目前,我采用了以下方法,但我不确定将来是否会给自己带来更多的头痛。

<StackPanel Grid.Row="0" Grid.Column="0">
  <Label Content="Boom" Style="{StaticResource DefaultInputStyle}" />
  <DatePicker Style="{StaticResource DefaultInputStyle}" />
</StackPanel>

这个想法最好能够使用这样的东西。

目前,我采用了以下方法,但我不确定将来是否会给自己带来更多的头痛。

<MyCoolControl Grid.Row="0" Grid.Column="0"
               Content="Boom"
               Style="{StaticResource DefaultInputStyle}" />

声明自定义控件

我不确定您是否可以为 Label 和 DatePicker 设置 DefaultInputStyle。什么是 DefaultInputStyle 的目标类型?如果要在多个应用程序中使用此自定义控件,建议使用自定义控件。如果要创建自定义控件,则需要从控件继承,请创建一些依赖项属性,重写 DefaultStyleKeyProperty。

public class MyCoolControl : Control
{
  public Style LabeStyle
  {
    get { return (Style)GetValue(LabeStyleProperty); }
    set { SetValue(LabeStyleProperty, value); }
  }
  public static readonly DependencyProperty LabeStyleProperty =
    DependencyProperty.Register(
      "LabeStyle", typeof(Style), typeof(MyCoolControl));
  public Style DatePickerStyle
  {
    get { return (Style)GetValue(DatePickerStyleProperty); }
    set { SetValue(DatePickerStyleProperty, value); }
  }
  public static readonly DependencyProperty DatePickerStyleProperty =
    DependencyProperty.Register(
      "DatePickerStyle", typeof(Style), typeof(MyCoolControl));
  public object LabelContent
  {
    get { return (object)GetValue(LabelContentProperty); }
    set { SetValue(LabelContentProperty, value); }
  }
  public static readonly DependencyProperty LabelContentProperty =
    DependencyProperty.Register(
      "LabelContent", typeof(object), 
      typeof(MyCoolControl), new PropertyMetadata(null));
  static MyCoolControl()
  {
    DefaultStyleKeyProperty.OverrideMetadata(
      typeof(MyCoolControl), 
      new FrameworkPropertyMetadata(typeof(MyCoolControl)));
  }
}

在Themes/Generic.xaml中定义MyCoolControl的隐式样式:

<Style TargetType="local:MyCoolControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <StackPanel>
                    <Label Content="{TemplateBinding LabelContent}" Style="{TemplateBinding LabeStyle}" />
                    <DatePicker Style="{TemplateBinding DatePickerStyle}" />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

然后,可以使用自定义控件:

<local:MyCoolControl Grid.Row="0" Grid.Column="0"
           LabelContent="Boom" DatePickerStyle="{StaticResource DefaultInputDatePickerStyle}"
           LabelStyle="{StaticResource DefaultInputLabelStyle}" />