На самом деле есть способ (вроде). Вы можете создать свой собственный пользовательский элемент управления и переопределить функцию OnApplyTemplate для динамического изменения стиля.
Например, создайте пользовательский элемент управления следующим образом (я делаю это в Silverlight, но я полагаю, что все то же самое):
namespace SilverlightClassLibrary1
{
public class MyButton: Button
{
public string BackgroundColor { get; set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (BackgroundColor != null)
{
Rectangle r = this.GetTemplateChild("BackgroundGradient") as Rectangle;
if (r != null)
{
r.Fill = new SolidColorBrush(Color.FromArgb(255,
Convert.ToByte(BackgroundColor.Substring(1,2),16),
Convert.ToByte(BackgroundColor.Substring(3,2),16),
Convert.ToByte(BackgroundColor.Substring(5,2),16)));
}
}
}
}
}
Интересной частью является метод GetTemplateChild , который ищет элемент управления Rectangle с именем "BackgroundGradient". (Кстати, проще определить пользовательские элементы управления в отдельном проекте, поэтому создайте новый проект «Библиотека классов Silverlight», если вы этого еще не сделали, и вставьте его в этот проект.)
Затем добавьте новый файл словаря ресурсов, переопределите шаблон элемента управления и убедитесь, что у вас есть прямоугольник с именем «BackgroundGradient». В этом случае мы используем стандартный шаблон управления кнопками, который я немного сократил:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:SilverlightClassLibrary1;assembly=SilverlightClassLibrary1">
<Style TargetType="custom:MyButton">
<Setter Property="Background" Value="#FF1F3B53"/>
<Setter Property="Foreground" Value="#FF000000"/>
<Setter Property="Padding" Value="3"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FF617584" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Border x:Name="Background" CornerRadius="3" Background="White" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
<Grid Background="{TemplateBinding Background}" Margin="1">
<Border Opacity="0" x:Name="BackgroundAnimation" Background="#FF448DCA" />
<Rectangle x:Name="BackgroundGradient" Fill="White" >
</Rectangle>
</Grid>
</Border>
<ContentPresenter
x:Name="contentPresenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"/>
<Rectangle x:Name="DisabledVisualElement" RadiusX="3" RadiusY="3" Fill="#FFFFFFFF" Opacity="0" IsHitTestVisible="false" />
<Rectangle x:Name="FocusVisualElement" RadiusX="2" RadiusY="2" Margin="1" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Теперь вы можете объявить элемент управления кнопки и переопределить стиль, если хотите:
<UserControl x:Class="SilverlightApplication1.MainPage"
...
xmlns:custom="clr-namespace:SilverlightClassLibrary1;assembly=SilverlightClassLibrary1">
<custom:MyButton>Normal Button 1</custom:MyButton>
<custom:MyButton>Normal Button 2</custom:MyButton>
<custom:MyButton BackgroundColor="#8888cc">Customized Background</custom:MyButton>
Полагаю, вы могли бы стать еще умнее, пройти через имя ресурса или имя стиля и загрузить его динамически.
Затем вам необходимо включить ваш файл ресурсов как часть вашего приложения:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightApplication1.App"
>
<Application.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
и вы увидите изменения пользовательского свойства в конструкторе XAML.