簡體   English   中英

UserControl屬性的默認值

[英]Default value for property of UserControl

UserControl包含從Control派生的BorderBrush屬性。 我如何設置它的默認值,例如, Brushes.Black並使其可供開發人員使用我的控件設置?

我試圖在控件的xaml文件及其構造函數中的<UserControl>標簽中分配初始值,但是當我執行任何此操作時,將忽略為外部控件分配的值。

您通常會通過覆蓋UserControl派生類中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 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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM