以编程方式更改WPF中的按钮图标

时间:2011-05-11 22:23:03

标签: c# wpf button icons

我目前有一个按钮,上面有一个图标/图像。我在XAML中配置了按钮和图像:

<Button Height="69" HorizontalAlignment="Left" Margin="-2,0,0,0" Name="toggleBroadcast" VerticalAlignment="Top" Width="64" Grid.Row="1" Opacity="0.5" Click="changeBroadcastState_Click">
        <Image Source="Images\playIcon.png" />
</Button>

我需要能够以编程方式将此按钮的图像从playIcon更改为stopIcon。我怎么能这样做?

3 个答案:

答案 0 :(得分:30)

您可以通过事件处理程序更改按钮的内容来实现此目的。

您可以将“播放”图标和“停止”图标同时设置为Window.Resources下的资源:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Image x:Key="Play" Source="/WpfApplication1;component/Play_Icon.png" Height="50" Width="50" />
    <Image x:Key="Stop" Source="/WpfApplication1;component/Stop_Icon.png" Height="50" Width="50"/>
</Window.Resources>
<Grid>
    <Button Click="Button_Click" Name="MediaButton">
        <DynamicResource ResourceKey="Play"/>
    </Button>
</Grid>

现在,当单击按钮时,您只需将按钮的内容更改为其他资源(停止图标)即可。在按钮的事件处理程序中,您可以执行以下操作:

C#

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (MediaButton.Content == FindResource("Play"))
    {
        MediaButton.Content = FindResource("Stop");
    }
    else
    {
        MediaButton.Content = FindResource("Play");
    }
}

编辑:更短的符号

MediaButton.Content = FindResource(MediaButton.Content == FindResource("Play") ? "Stop" : "Play");

希望这有帮助,如果您有任何其他问题,请与我联系。

答案 1 :(得分:5)

如果您的图像定义如下:

<Image Source="{Binding ImageSource}" Stretch="Fill"/>

然后在您想要进行切换的代码中,只需:

ImageSource = image;

其中image定义为:

image = new BitmapImage(new Uri("/Application;component/Resources/pause.png", UriKind.Relative));

当然,它依赖于您使用MVVM模式并在代码中实现INotifyPropertyChanged接口。

答案 2 :(得分:3)

在更改条件下,在图像样式(/ edit)中使用DataTrigger (编辑)

<Button Height="69" HorizontalAlignment="Left" Margin="-2,0,0,0" Name="toggleBroadcast" VerticalAlignment="Top" Width="64" Grid.Row="1" Opacity="0.5" Click="changeBroadcastState_Click">
    <Image>
        <Image.Style>        
            <Style TargetType="{x:Type Image}">
                <Setter Property="Source" Value="Images\playIcon.png" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding myCondition}" Value="True">
                        <Setter Property="Source" Value="Images\stopIcon.png" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>        
    </Image>
</Button>

myCondition变量将是ViewModel中的布尔属性(或者,更一般地说,是Control的DataContext),类似于

public bool myCondition { get { return ([whatever that condition might be]); } }

这也可能包括一个setter,也可能是一个简单的自动属性。与其他MVVM答案一样,它将依赖ViewModel来实现INotifyPropertyChanged

好处是,一旦条件不再满足,DataTrigger将自动将Source属性设置回原始值。

免责声明:我现在无法对此进行测试,所以请谨慎使用,并进行一些调试......

相关问题