UserControl
包含从Control
继承的BorderBrush
属性。我应该如何设置它的默认值,例如为Brushes.Black
,并使其可供使用我的控件的开发人员设置?
我尝试在控件的xaml文件中的<UserControl>
标记和构造函数中分配初始值,但是当我这样做时,外部分配给控件的值会被忽略。
UserControl
包含从Control
继承的BorderBrush
属性。我应该如何设置它的默认值,例如为Brushes.Black
,并使其可供使用我的控件的开发人员设置?
我尝试在控件的xaml文件中的<UserControl>
标记和构造函数中分配初始值,但是当我这样做时,外部分配给控件的值会被忽略。
BorderBrush
属性的元数据来实现此操作:public partial class MyUserControl : UserControl
{
static MyUserControl()
{
BorderBrushProperty.OverrideMetadata(
typeof(MyUserControl),
new FrameworkPropertyMetadata(Brushes.Black));
}
public MyUserControl()
{
InitializeComponent();
}
}
<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>
<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>
<ctrls:BorderedControl Width="100"
Height="100"
BorderBrush="Orange"/>