簡體   English   中英

在Generic.xaml中找不到命名樣式

[英]Not finding named style in Generic.xaml

我有以下自定義控件

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

使用以下主題/ Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication4">

<Style TargetType="{x:Type l:MagicButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type l:MagicButton}">
                <Border />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type l:MagicButton}"
       x:Key="OtherStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type l:MagicButton}">
                <Border />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

當我使用默認樣式使用MagicButton控件時,一切正常,但當我嘗試使用“OtherStyle”時

<l:MagicButton Style="{StaticResource OtherStyle}"/>

它找不到具有異常“{”的樣式,找不到名為'OtherStyle'的資源。 資源名稱區分大小寫。“}”

然而,如果我將OtherStyle移動到App.xaml它可以工作。

我不想把它放在App.xaml中,我想要的是我的Themes / Generic.xaml文件包含默認樣式以及人們可以明確選擇使用的鍵命名樣式

由於generic.xaml文件沒有代碼,我們無法創建它的實例來從中讀取Style CustomControl使用DefaultStyleKey從中訪問Style ,如您在示例中所示。 因此,您無法以其他方式訪問它。

但是,與所有其他控件一樣, Application.Resources是為此控件定義自定義Style的正確位置。 你非常樂意為Button定義Style ,或者在那里定義任何其他.NET控件,為什么不為你自己的控件呢?


更新>>>

它不是特定於應用程序的樣式,它是我想要保留在theme / Generic.xml中的控件的替代樣式,以便引用該主題的任何項目也可以使用它。

是的,但你試圖在generic.xaml之外引用它,你不能......它不像Application.Resources 可以做的是在你的控件中添加一個DependencyProperty ,它在內部設置不同的Style

暫無
暫無

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

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