在wpf中更改模板化按钮的图像

时间:2015-10-30 07:48:58

标签: wpf

我有一个模板化的wpf按钮。我必须在运行时更改图像。

xaml代码:

<Window.Resources>
        <Image x:Key="imgPlay" Source="Media/Knob Play.png"></Image>
        <Image x:Key="imgStop" Source="Media/Knob Red.png"></Image>
        <ControlTemplate x:Key="custom-button" TargetType="Button">
            <Grid x:Name="btn_image">
                <!--<Grid.Background>
                    <ImageBrush  ImageSource="Media/Knob Red.png"></ImageBrush>
                </Grid.Background>-->
                <!--<Image  Source="Media/Knob Red.png"></Image>-->
            </Grid>
        </ControlTemplate>
    </Window.Resources>

按钮我需要更改:

<Button Name="start" Template="{DynamicResource  custom-button}"  HorizontalAlignment="Left" Margin="147,67,0,0" VerticalAlignment="Top" Width="37" Height="30" Click="Start_Click">
                <DynamicResource ResourceKey="imgStop"></DynamicResource>
 </Button>

代码隐藏:

private void Start_Click(object sender, RoutedEventArgs e)
        {
            if (sw.IsRunning)
            {
                start.Content = FindResource("imgStop");
                sw.Stop();
                dt.Stop();
            }
            else
            {
                sw.Start();
                dt.Start();

                start.Content = FindResource("imgPlay");
            }
        }

在SO和网络中尝试了许多解决方案。没有任何效果。

1 个答案:

答案 0 :(得分:0)

也许你可以从中获得灵感......

资源

<Window.Resources>
    <ControlTemplate x:Key="option1" TargetType="Button">
        <TextBlock  Foreground="Red">ClickMe</TextBlock>    
    </ControlTemplate>

    <ControlTemplate x:Key="option2" TargetType="Button">
        <TextBlock Foreground="Green">Template is changed</TextBlock>
    </ControlTemplate>
</Window.Resources>

XAML:

<Grid Width="100" Height="100">
    <Button Name="theButton" Click="OnClick" Template="{StaticResource option1}"/>
</Grid>

代码背后:

private void OnClick(object sender, RoutedEventArgs e)
{
     this.theButton.Template = (ControlTemplate)FindResource("option2");
}