2

我正在创建一个自定义控件库,并从一个简单的圆形边缘分隔符开始,但有些事情我似乎无法做到。

我有一个 CornerRadius 依赖属性,如果 CornerRadius 未定义,我希望 CornerRadius 等于 Height / 2,否则取用户值。我在构造函数中初始化高度,使其永远不会为空

我知道如何定义依赖属性的默认值,但我不知道如何,或者是否可以根据控件的高度设置 CornerRadius 值。到目前为止,我已经搜索了一段时间。

Xaml 文件

<!-- Rounded Separator -->
<Style TargetType="{x:Type local:RoundedSeparator}" BasedOn="{StaticResource {x:Type Separator}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:RoundedSeparator}">

                <!-- Mask for round edges -->
                <Grid Height="{TemplateBinding Height}"
                      Width="{TemplateBinding Width}">
                    <Border Name="PART_TitleBarMask" 
                            CornerRadius="{TemplateBinding CornerRadius}"
                            Background="White"/>

                    <Grid>
                        <Grid.OpacityMask>
                            <VisualBrush Visual="{Binding ElementName=PART_TitleBarMask}"/>
                        </Grid.OpacityMask>

                        <!-- Separator -->
                        <Rectangle Fill="{TemplateBinding Background}"/>
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

.cs 文件

public class RoundedSeparator : Separator
{
    static RoundedSeparator()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(RoundedSeparator), new FrameworkPropertyMetadata(typeof(RoundedSeparator)));
    }

    public RoundedSeparator()
    {
        this.Height = 100;
        this.Background = Brushes.Black;
    }

    public static readonly DependencyProperty CornerRadiusProperty = 
        DependencyProperty.Register("CornerRadius", 
                                    typeof(CornerRadius), 
                                    typeof(RoundedSeparator), 
                                    new UIPropertyMetadata(default(CornerRadius));

    public CornerRadius CornerRadius
    {
        get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        set { SetValue(CornerRadiusProperty, value); }
    }
}
4

1 回答 1

0

尝试 :

  static RoundedSeparator()
  {
       DefaultStyleKeyProperty.OverrideMetadata(typeof(RoundedSeparator), new FrameworkPropertyMetadata(typeof(RoundedSeparator)));

      RoundedSeparator.HeightProperty.OverrideMetadata
               (typeof(RoundedSeparator), new FrameworkPropertyMetadata(new PropertyChangedCallback(HeightPropertyChanged)));
  }


  private static void HeightPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
         // Do what you will .... :)
  }
于 2013-09-02T15:59:33.787 回答