我无法让此按钮(其内容中包含图像)正确更改ImageSource
点击。这是我的 Xaml 和代码背后。
XAML:
<Window.Resources>
<Style x:Key="NoChromeButton" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Transparent"/>
<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}">
<Grid x:Name="Chrome" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
<Setter Property="Opacity" TargetName="Chrome" Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button x:Name="DrawCircleButton" Height="56" Width="157"
Margin="10,10,0,0" VerticalAlignment="Top"
HorizontalAlignment="Left" Click="DrawCircleButtonClick"
Style="{DynamicResource NoChromeButton}"
>
<Image x:Name="imgButtonState" >
<Image.Source>
<BitmapImage UriSource="Resources/off.gif" />
</Image.Source>
</Image>
</Button>
<ScrollViewer Margin="0,50,0,0">
<TextBlock Name="textBlock1" TextWrapping="Wrap" FontSize="20" FontWeight="Bold" />
</ScrollViewer>
</Grid>
代码背后:
private void DrawCircleButtonClick(object sender, RoutedEventArgs e)
{
var t = ButtonState;
ButtonState = t;
}
public bool ButtonState
{
get
{
return (bool)GetValue(ButtonStateProperty);
}
set
{
var t = new BitmapImage(new Uri("Resource/on.gif", UriKind.Relative));
DrawCircleButton.Content = !value ? imgButtonState.Source = new BitmapImage(new Uri("on.gif", UriKind.Relative)) : imgButtonState.Source = new BitmapImage(new Uri("off.gif", UriKind.Relative));
SetValue(ButtonStateProperty, !value);
}
}
public static readonly DependencyProperty ButtonStateProperty = DependencyProperty.Register("ButtonState", typeof(bool), typeof(bool));
因此,最初,该按钮设置为“关闭”。但是当它被点击时,它会在“开”和“关”之间切换。我确定我做错了什么,因为显示的是图像路径的文本。有任何想法吗?