[英]Setting the style of a WPF UserControl
我知道我可以通過添加一個屬性在UserControl
像這樣設置UserControl
的樣式:
Style="{StaticResource MyStyle}"
並且在我的ResourceDictionary
中具有如下所示的樣式:
<Style x:Key="MyStyle" TargetType="{x:Type UserControl}">
<Style.Resources>
<Style TargetType="Label">
<!-- Label Setters -->
</Style>
<Style TargetType="TextBox">
<!-- TextBox Setters -->
</Style>
</Style.Resources>
</Style>
但是有沒有一種方法可以直接在ResourceDictionary
設置UserControl
的樣式,例如:
<Style x:Key="MyStyle" TargetType="{x:Type MyControl}">
基本上我的問題是,我可以將樣式直接應用於控件而不是控件組件嗎?
編輯:我想要完成的事情如下:
<Style x:Key="MyStyle" TargetType="{x:Type MyControl}">
<Setter Property="Background" Value="Black"/>
</Style>
<Style x:Key="{x:Type MyControl}" TargetType="{x:Type MyControl}" BasedOn="{StaticResource MyStyle}"/>
第二行將樣式應用於應用程序中的所有控件,如果您對普通控件執行類似操作,則此方法有效。
然而,這只設置了UserControl
的Background
,所以我如何將相同的背景應用到它的組件。
我怎樣才能用UserControl
做到這一點?
您可以像這樣直接設置 UserControl 的樣式:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style>
<Setter Property="local:MyControl.MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
或者像這樣:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
UserControl 資源中的默認樣式也應該有效:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Resources>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Resources>
</UserControl>
您需要從定義的樣式中刪除x:Key
,以便它可以普遍應用於與TargetType
定義的類型相同的所有控件。
從 MSDN 引用Style.TargetType 屬性:
將 TargetType 屬性設置為 TextBlock 類型而不設置 x:Key 將 x:Key 隱式設置為 {x:Type TextBlock}。 這也意味着,如果您給 [...] 樣式一個 x:Key 值而不是 {x:Type TextBlock},樣式將不會自動應用於所有 TextBlock 元素。 相反,您需要將樣式顯式應用於 TextBlock 元素。
要設置所有控件的樣式,請將您的 ResourceDictionary 添加到 App.xaml 的資源中。
<Application.Resources>
<!-- Your Resources for the whole application here -->
</Application.Resources>
如果您使用應用程序打開主窗口...
<Application ...
MainWindow="MainWindow">
或在啟動事件期間...
<Application ...
MainWindow="MainWindow">
Startup="Application_Startup">
資源在 MainWindow 的每個控件中都可用。
在您的用戶控件 xaml 中,將樣式放置在資源標簽內:
<UserControl>
<UserControl.Resources>
<Style ...</Style>
</UserControl.Resources>
//.. my other components
</UserControl>
Necro 對特殊情況的回答。 如果通過另一個 WPF 控件或窗口中的 DataTemplate 資源選擇用戶控件,WPF 可能不會自動應用導入的資源字典中的默認樣式。 但是,您可以在導入資源字典后應用命名樣式資源。
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../../Resources/ResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.Style>
<Binding Source="{StaticResource MyUserControlStyle}"></Binding>
</UserControl.Style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.