【发布时间】:2022-01-03 18:00:28
【问题描述】:
我有以下代码用于自定义 WPF 单选按钮,其中包含图像作为内容。 图像构建操作设置为“内容”,复制到输出目录设置为“如果较新则复制”。
<!--MaterialButtonTheme-->
<Style BasedOn="{StaticResource {x:Type ToggleButton}}"
TargetType="{x:Type RadioButton}"
x:Key="MaterialButtonTheme">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Background="{TemplateBinding Background}">
<Border>
<Image Source="{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Opacity" Value=".3"/>
<Setter Property="BorderThickness" Value="0"/>
</Style.Setters>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value=".8"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Opacity" Value=".6"/>
</Trigger>
</Style.Triggers>
</Style>
现在,我不想对图像资源使用硬代码变体,但以下方法不起作用。
<RadioButton
x:Name="RadioButtonSteelMat"
Height="30" Width="30"
Foreground="White"
HorizontalAlignment="Left"
FontSize="14"
Style="{StaticResource MaterialButtonTheme}"
Content="../EmbeddedResources/Images/steel.png"
IsChecked="False"
Margin="10,200,0,0"
Checked="RadioButtonSteelMat_Checked"
/>
以下硬编码变体可以正常工作。有人知道我做错了什么吗?
<RadioButton
x:Name="RadioButtonSteelMat"
Height="30" Width="30"
Foreground="White"
HorizontalAlignment="Left"
FontSize="14"
Style="{StaticResource MaterialButtonTheme}"
Content="C:\Users\Niklas\Desktop\Studium\Master\M4\Thesis\Tool\OptioneeringTool\OptioneeringTool\B+GOpt\EmbeddedResources\Images\steel.png"
IsChecked="False"
Margin="10,200,0,0"
Checked="RadioButtonSteelMat_Checked"
/>
【问题讨论】:
-
在 WPF 应用程序中,您通常会将图像文件的 Build Action 设置为
Resource并通过 Resource File Pack URI 加载它,例如"pack://application:,,,/EmbeddedResources/Images/steel.png"。您可能必须使用 XAML 元素语法来设置内容:<RadioButton ...><BitmapImage UriSource="pack://application:,,,/EmbeddedResources/Images/steel.png"/></RadioButton> -
真的必须是png吗?我更喜欢一条路。或者如果它绝对必须是多种颜色,则可以使用绘图视觉。材料设计是扁平的,所以我本来希望有一条可行的路径。
-
如果您不想将图像作为资源嵌入,您可以使用
siteoforigin而不是applicationpack uri。"pack://siteoforigin:,,,/EmbeddedResources/Images/steel.png"docs.microsoft.com/en-us/dotnet/desktop/wpf/app-development/…
标签: c# wpf radio-button controls