2014-06-22 58 views
1

我有以下的自定義控制沒有找到命名風格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不過,我想是我的主題/ Generic.xaml文件包含默認樣式,以及命名鍵樣式,人們可以明確地選擇加入到使用

+2

檢查你的代碼,我有測試,沒有錯誤。 ' – Rang

+0

'Themes/Generic.xaml'與試圖使用'OtherStyle'的代碼位於同一個項目中。爲什麼我必須顯式添加ResourceDictionary?它似乎沒有這樣做的默認風格。 – wforl

回答

3

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

但是,與所有其他控件一樣,Application.Resources是用於定義此控件的自定義Style的正確位置。您很樂意爲Button或其他任何.NET控件定義Style,那麼爲什麼不適合您自己的控件呢?


UPDATE >>>

它不是一個專用的風格,它的另一種風格的控制,我想保持在主題/ Generic.xml使任何項目引用主題也可以使用它。

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

+0

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