UserControl 属性 的默认值

Default value for property of UserControl

UserControl 包含源自 ControlBorderBrush 属性。我如何设置它的默认值,例如 Brushes.Black 并使其可供将使用我的控件的开发人员设置?

我试图在控件的 xaml 文件及其构造函数中的 <UserControl> 标记中分配初始值,但是当我这样做时,为控件分配的值 外部被忽略。

您通常会通过在派生的 class:

的用户控件中覆盖 BorderBrush 属性 的元数据来实现此目的
public partial class MyUserControl : UserControl
{
    static MyUserControl()
    {
        BorderBrushProperty.OverrideMetadata(
            typeof(MyUserControl),
            new FrameworkPropertyMetadata(Brushes.Black));
    }

    public MyUserControl()
    {
        InitializeComponent();
    }
}

也许款式最好。您可以创建一个新的 UserControl,我们称它为 BorderedControl。我创建了一个名为 Controls 的新文件夹来保存它。

<UserControl x:Class="BorderTest.Controls.BorderedControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>

</Grid>
</UserControl>

接下来,创建资源字典 UserControlResources。请务必包含控件的命名空间:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctrls="clr-namespace:BorderTest.Controls">
    <Style TargetType="{x:Type ctrls:BorderedControl}">
        <Setter Property="BorderBrush" Value="Lime"/>
        <Setter Property="BorderThickness" Value="3"/>
    </Style>
</ResourceDictionary>

在这里您可以设置您想要的默认属性。

然后,在用户控件资源中包含资源字典:

<UserControl x:Class="BorderTest.Controls.BorderedControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <ResourceDictionary Source="/BorderTest;component/Resources/UserControlResources.xaml"/>
</UserControl.Resources>
<Grid>

</Grid>
</UserControl>

最后,将控件添加到主 window:

<Window x:Class="BorderTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctrls="clr-namespace:BorderTest.Controls"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ctrls:BorderedControl Width="100"
                           Height="100"/>
</Grid>
</Window>

这是我的解决方案:

这是您 运行 时的应用程序:

您可以简单地更改用户控件的边框:

<ctrls:BorderedControl Width="100"
                       Height="100"
                       BorderBrush="Orange"/>