简体   繁体   中英

WPF button icon change programmatically

I want to change icon of the following button programmatically

<Button x:Name="btnSendInvite" Height="32" Background="Transparent" BorderBrush="Transparent"
    BorderThickness="0" Cursor="Hand" Margin="1,5" ToolTip="Call" Click="btnSendInvite_Click" >
                    <Button.Template>
                        <ControlTemplate TargetType="Button">

                                <DockPanel>
                                    <DockPanel.Background>
                                        <ImageBrush ImageSource="Resources/button.png" />
                                    </DockPanel.Background>
                                    <StackPanel Orientation="Horizontal">
                                        <Image Source="Resources/dial.png" Height="30" Margin="14,0"></Image>
                                    </StackPanel>
                                </DockPanel>

                        </ControlTemplate>
                    </Button.Template>
                    <Button.Style>
                        <Style TargetType="Button">
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="Black"/>
                                    <Setter Property="Foreground" Value="White"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>

Need to change dial.png icon to hangup.png . How it possible in c#

If you absolutely have to change the image using code, then you should data bind the Image.Source property and then change your data bound image path:

<StackPanel Orientation="Horizontal">
    <Image Source="{Binding ImageSource}" Height="30" Margin="14,0" />
</StackPanel>

The default value for your new property would be Resources/dial.png and you could change it like so:

ImageSource = "Resources/hangup.png";

Of course, your ImageSource property must notify the INotifyPropertyChanged Interface of the change so that the UI can update the Image . However, it must be said that using a Trigger or DataTrigger to change the Image.Source in XAML would be a better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM