[英]How can I bind to dependency properties of a custom control from a resource dictionary defined in Generic.xaml?
[英]How can I make a Custom Control automatically apply a style defined in a resource dictionary?
我有一個帶有自定義控件的控件庫:
public class GlassButton : Button {
}
並且我還定義了資源字典來設置控件的樣式:
<ResourceDictionary
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"
xmlns:Animations="clr-namespace:WPFTools.Classes"
xmlns:Controls="clr-namespace:WPFTools.Controls"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d">
<Style TargetType="{x:Type Controls:GlassButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
我希望能夠簡單地將GlassButton
拖放到窗口或控件上,而不必這樣做:
<Window.Resources>
<ResourceDictionary Source="Foo"/>
</Window.Resources>
我以前曾經做過一次,但是那知識似乎已經對我丟失了。
我怎樣才能做到這一點? (我很好地更改了控件背后的代碼)。
我不得不記得一個星期前它是如何工作的,這是我必須做的才能使其對我有用。 使用自定義控件的典型方法是在項目根目錄下“ Themes
文件夾中的名為generic.xaml
的文件中定義樣式。 然后,您需要在自定義控件類的靜態構造函數中覆蓋默認樣式。 它看起來像這樣:
public class GlassButton : Button
{
static GlassButton()
{
DefaultStyleKeyProperty.OverrideMetadata( typeof( GlassButton ),
new FrameworkPropertyMetadata( typeof( GlassButton ) ) );
}
}
最后,您需要設置適當的程序集屬性以說通用主題位於程序集中。 這樣的事情會出現在您的Properties\\AssemblyInfo.cs
文件中:
using System.Windows;
[assembly:ThemeInfo( ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly )]
我不確定這是否絕對必要,但是在將默認樣式正確應用於控件之前,我還必須將generic.xaml
文件上的“生成操作”屬性更改為Page。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.