在运行时更改样式 [英] Change style during runtime
本文介绍了在运行时更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个保存在 App.xaml 中的 wpf 按钮模板.在这个按钮模板中,有一个图像控件.我想用这个模板创建一个新按钮,并在运行时向它添加一个图像源.
Hi i have a wpf button template saved in App.xaml. Inside this button template, there is an image control. I want to create a new button with this template and add an image source to it at runtime.
<Style x:Key="newbutton" TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
<Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
<Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding IsDefaulted}" SnapsToDevicePixels="true">
!!!!!!!!!!!!!THIS GUY HERE>>>>>>>>>>>>>>>><Image HorizontalAlignment="Left" Height="17.96" VerticalAlignment="Top" Width="71"/>**
</Themes:ButtonChrome>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="true">
<Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
推荐答案
you can create attach DependencyProperty
you could create attached DependencyProperty
public static class AttachedProperties
{
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(AttachedProperties), new UIPropertyMetadata(null));
public static void SetImageSource(DependencyObject d, ImageSource source)
{
d.SetValue(ImageSourceProperty, source);
}
public static ImageSource GetImageSource(DependencyObject d)
{
return (ImageSource)d.GetValue(ImageSourceProperty);
}
}
然后在模板中使用 TemplatedParent
<ControlTemplate TargetType="{x:Type Button}">
<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:AttachedProperties.ImageSource)}"/>
</ControlTemplate>
然后你可以在Setter
<Setter Property="local:AttachedProperties.ImageSource" Value="..."/>
或者直接针对Button
<Button local:AttachedProperties.ImageSource="..." .../>
这篇关于在运行时更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文