UserControl属性的默认值

4

UserControl包含从Control继承的BorderBrush属性。我应该如何设置它的默认值,例如为Brushes.Black,并使其可供使用我的控件的开发人员设置?

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


CSharper的回答绑定到设置中定义的值这个问题上可行吗? - Sometowngeek
@Sometowngeek 不知道,现在无法检查,因为一年前转为了aspnet开发人员。 - FLCL
2个回答

7
通常可以通过在您的UserControl派生类中覆盖BorderBrush属性的元数据来实现此操作:
public partial class MyUserControl : UserControl
{
    static MyUserControl()
    {
        BorderBrushProperty.OverrideMetadata(
            typeof(MyUserControl),
            new FrameworkPropertyMetadata(Brushes.Black));
    }

    public MyUserControl()
    {
        InitializeComponent();
    }
}

3
也许样式是最好的选择。您可以创建一个新的用户控件,我们称其为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 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>

这是我的解决方案:

My Solution

当你运行应用程序时,它会显示如下界面:

Run

你可以使用以下代码来简单地更改用户控件的边框:
<ctrls:BorderedControl Width="100"
                       Height="100"
                       BorderBrush="Orange"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接