Wpf 从resourcedictionary中选择图像源路径
我有一个复选框,我用自定义图像设置样式。 我需要在运行时根据主题选择一个图像。 我只想改变图像,而不是所有的模板。 这是我的复选框模板:Wpf 从resourcedictionary中选择图像源路径,wpf,resourcedictionary,Wpf,Resourcedictionary,我有一个复选框,我用自定义图像设置样式。 我需要在运行时根据主题选择一个图像。 我只想改变图像,而不是所有的模板。 这是我的复选框模板: <Style TargetType="{x:Type CheckBox}" x:Key="FlatCheckbox"> <Setter Property="Template"> <Setter.Value>
<Style TargetType="{x:Type CheckBox}" x:Key="FlatCheckbox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<StackPanel Orientation="Horizontal">
<Image x:Name="checkboxImage" Source="/checked.png" Width="32"/>
<ContentPresenter/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="checkboxImage" Property="Source" Value="/unchecked.png"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
所以我只想从ResourceDictionary(我可以在运行时选择)获取checkboxImage的源路径
例如,如果我可以在ResourceDictionary中放置一个键ImagePath并使用类似的内容
<Image x:Name="checkboxImage" Source="{ImagePath}" Width="32"/>
如何实现此目的?您可以将位图图像声明为XAML资源,并将其引用为
DynamicSource
,例如:
<Window.Resources>
<BitmapImage x:Key="TestImage" UriSource="Image1.jpg"/>
<Style x:Key="TestStyle" TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Image Source="{DynamicResource TestImage}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ContentControl Style="{StaticResource TestStyle}"/>
</Grid>
public MainWindow()
{
InitializeComponent();
Resources["TestImage"] =
new BitmapImage(new Uri("pack://application:,,,/Image2.jpg"));
}