我正在尝试通过附加属性更改我作为按钮内容放置的图像,但由于某种原因,图像没有改变,我在输出中没有得到任何异常或任何可靠的东西。这是我附加的属性类代码:
public class ImageButton
{ #region 图片依赖属性
/// <summary>
/// An attached dependency property which provides an
/// <see cref="ImageSource" /> for arbitrary WPF elements.
/// </summary>
public static DependencyProperty ImageProperty;
/// <summary>
/// Gets the <see cref="ImageProperty"/> for a given
/// <see cref="DependencyObject"/>, which provides an
/// <see cref="ImageSource" /> for arbitrary WPF elements.
/// </summary>
public static ImageSource GetImage(DependencyObject obj)
{
return (ImageSource)obj.GetValue(ImageProperty);
}
/// <summary>
/// Sets the attached <see cref="ImageProperty"/> for a given
/// <see cref="DependencyObject"/>, which provides an
/// <see cref="ImageSource" /> for arbitrary WPF elements.
/// </summary>
public static void SetImage(DependencyObject obj, ImageSource value)
{
obj.SetValue(ImageProperty, value);
}
#endregion
static ImageButton()
{
//register attached dependency property
var metadataImage = new FrameworkPropertyMetadata((ImageSource)null);
ImageProperty = DependencyProperty.RegisterAttached("Image",
typeof(ImageSource),
typeof(ImageButton), metadataImage);
}
}
这里使用附加属性的样式代码(图像源设置为取值):
<Style TargetType="{x:Type Button}" x:Key="MyImageButton">
<Setter Property="Background" Value="White"/>
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border
x:Name="Border"
Background="White">
<ContentPresenter>
<ContentPresenter.Content>
<Grid
x:Name="Grid"
Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image
Grid.Column="0"
Source="{Binding Path=(attachedProperties:ImageButton.Image),
RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}"
Width="30"
Height="25"
Margin="5,0,2,0"
VerticalAlignment="Center"/>
<TextBlock
x:Name="TextBlock"
Grid.Column="1"
Text="{Binding Path=(attachedProperties:ImageButton.StringContent),
RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}"
VerticalAlignment="Center"
TextAlignment="Center"
Margin="0,0,15,0"/>
</Grid>
</ContentPresenter.Content>
</ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最后是使用样式的 XAML 代码和尝试更改图像源的触发器:
<Button
Grid.Row="2"
Width="30"
attachedProperties:ImageButton.Image="..\Images\Down_Arrow_Enabled_Icon_25x25.png"
Command="{Binding PriorityDownCommand}">
<Button.Style>
<Style TargetType="{x:Type Button}"
BasedOn="{StaticResource MyImageButton}">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="attachedProperties:ImageButton.Image" Value="..\Images\Down_Arrow_Disabled_Icon_25x25.png"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
提前感谢任何能找到问题的人!!!