繁体   English   中英

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

[英]Create button with image programmatically

在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 ,然后将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;

var image = new Image(); image.Source = SoundDisable; btnSound.Content = image;

topBar.Children.Add(btnSound);

更改图像:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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