Reputation: 885
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>
Upvotes: 1
Views: 432
Reputation: 33364
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);
}
}
then in template use AttachedProperties.ImageSource
of TemplatedParent
<ControlTemplate TargetType="{x:Type Button}">
<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:AttachedProperties.ImageSource)}"/>
</ControlTemplate>
and then you can either set it in the Setter
<Setter Property="local:AttachedProperties.ImageSource" Value="..."/>
or set it directly against Button
<Button local:AttachedProperties.ImageSource="..." .../>
Upvotes: 1