自定义控件:
using System.Windows;
using System.Windows.Controls;
namespace Test
{
public class KeyboardButton : Button
{
public static readonly DependencyProperty SelectedKeyProperty = DependencyProperty.Register("SelectedKey", typeof(string),
typeof(KeyboardButton), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty IsUpperCaseProperty = DependencyProperty.Register("IsUpperCase", typeof(bool),
typeof(KeyboardButton), new FrameworkPropertyMetadata(false));
static KeyboardButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(KeyboardButton), new FrameworkPropertyMetadata(typeof(KeyboardButton)));
}
public string SelectedKey
{
get { return (string)GetValue(SelectedKeyProperty); }
set { SetValue(SelectedKeyProperty, value); }
}
public string LowerCaseKey
{
get;
set;
}
public string UpperCaseKey
{
get;
set;
}
public bool IsUpperCase
{
get { return (bool)GetValue(IsUpperCaseProperty); }
set { SetValue(IsUpperCaseProperty, value); }
}
}
}
Themes\Generic.xaml(主题文件夹中的文件 Generic.xaml)
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Test">
<Style TargetType="{x:Type local:KeyboardButton}" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Content" Value="{Binding LowerCaseKey, Mode=OneTime, RelativeSource={RelativeSource Self}}"/>
<Style.Triggers>
<Trigger Property="IsUpperCase" Value="true">
<Setter Property="Content" Value="{Binding UpperCaseKey, Mode=OneTime, RelativeSource={RelativeSource Self}}"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
不要在 AssemblyInfo.cs 中忘记这一点:
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]