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

时间:2014-07-15 08:34:01

标签: c# windows-phone-8.1

在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版本中,我使用

设置了Image
speakerImg.Source = SoundDisable;

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

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

1 个答案:

答案 0 :(得分:5)

简单:添加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;