gpt4 book ai didi

c# - 以编程方式创建带有图像的按钮

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:21 25 4
gpt4 key购买 nike

在 XAML 中很容易定义带有图像的按钮:

<Button x:Name="btnSound"
Click="SoundButton"
Height="40"
HorizontalAlignment="Left"
VerticalAlignment="Bottom" Margin="20,0">
<Image x:Name="speakerImg" Source="/png/btn_speak_i.png" />
</Button>

我想在 c# 中这样做:

// Prepare two BitmapImages
BitmapImage SoundDisable = new BitmapImage(new Uri("ms-appx:///png/btn_speak_i.png",
UriKind.RelativeOrAbsolute));
BitmapImage SoundEnable = new BitmapImage(new Uri("ms-appx:///png/btn_speak.png",
UriKind.RelativeOrAbsolute));

// Define and Load Button
btnSound = new Button();
btnSound.HorizontalAlignment = HorizontalAlignment.Left;
btnSound.VerticalAlignment = VerticalAlignment.Bottom;
Thickness margin = new Thickness(0,00,20,0);
btnSound.Margin = margin;
btnSound.Click += new RoutedEventHandler(btnSound_Click);
btnSound.IsEnabled = false;
topBar.Children.Add(btnSound);

我找不到向按钮添加图像的方法。有点像

btnSound.Content = SoundDisable; 

不工作。它仅显示带有按钮内图像类型的文本。在 XAML 版本中,我将图像设置为

speakerImg.Source = SoundDisable;

因为图像是用 x:Name 定义的。

如何以编程方式将命名图像添加到我的按钮?

最佳答案

简单:添加一个Image,并将图像Source设置为您的BitmapImage

// Prepare two BitmapImages
BitmapImage SoundDisable = new BitmapImage(new Uri("ms-appx:///png/btn_speak_i.png",
UriKind.RelativeOrAbsolute));
BitmapImage SoundEnable = new BitmapImage(new Uri("ms-appx:///png/btn_speak.png",
UriKind.RelativeOrAbsolute));

// Define and Load Button
btnSound = new Button();
btnSound.HorizontalAlignment = HorizontalAlignment.Left;
btnSound.VerticalAlignment = VerticalAlignment.Bottom;
Thickness margin = new Thickness(0,00,20,0);
btnSound.Margin = margin;
btnSound.Click += new RoutedEventHandler(btnSound_Click);
btnSound.IsEnabled = false;

<strong>var image = new Image();
image.Source = SoundDisable;
btnSound.Content = image;</strong>

topBar.Children.Add(btnSound);

To change the image:

((Image)btnSound.Content).Source = SoundEnable;

关于c# - 以编程方式创建带有图像的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24753453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com