嗯,它并不是真正的动态的,至少在运行时不会改变。
我的想法是有几个按钮,每个按钮都有一个独特的图像(32x32的图标)。所有按钮共享一种样式,我在ControlTemplate中进行了修改。因此,每个图像也有两种颜色,一种是正常的,另一种是鼠标悬停时的颜色。
我注意到当我声明图像的源路径时,它们几乎都是相同的,所以我想DRY(不要重复自己)。如果我可以使用按钮名称或其他属性作为源路径的一部分(即图像文件的名称),那就是好的编程。
问题是我对XAML、WPF和可能的编程都很陌生,所以我不知道该怎么做。我想这需要代码后台或某种转换器(我猜我会再多读一些关于转换器的资料)。这里有一点代码(这不起作用,但它给你一个大致的想法(希望如此)):
<Style x:Key="ButtonPanelBigButton" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="ButtonBorder"
Height="78"
MaxWidth="70"
MinWidth="50"
BorderThickness="0.5"
BorderBrush="Transparent"
CornerRadius="8" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Here I wan't to put in the Name property of the button because there is a picture there to match -->
<Image x:Name="ButtonIcon" Source="..\Images\Icons\32x32\Blue\{Binding Name}.png"
Margin="4"
Height="32"
Width="32"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
<TextBlock Grid.Row="1"
Padding="5,2,5,2"
TextWrapping="Wrap"
Style="{StaticResource MenuText}"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ContentPresenter ContentSource="Content" />
</TextBlock>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True" >
<Setter TargetName="ButtonIcon" Property="Source" Value="..\Images\Icons\32x32\Green\user.png" /> <!-- Same Here -->
<Setter TargetName="ButtonBorder" Property="BorderBrush" Value="{StaticResource SecondColorBrush}" />
<Setter TargetName="ButtonBorder" Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1" Opacity="0.5">
<GradientStop Color="{StaticResource MainColor}" Offset="1" />
<GradientStop Color="{StaticResource SecondColor}" Offset="0.5" />
<GradientStop Color="{StaticResource MainColor}" Offset="0" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
希望你能理解我的意思,帮助我将代码变得更加简洁(我现在又在重复自己!)。