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

thp*_*sch 1 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>
Run Code Online (Sandbox Code Playgroud)

我想这样做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);
Run Code Online (Sandbox Code Playgroud)

我找不到将图像添加到按钮的方法.就像是

btnSound.Content = SoundDisable; 
Run Code Online (Sandbox Code Playgroud)

不管用.它仅显示带有按钮内图像类型的文本.在XAML版本中,我设置了图像

speakerImg.Source = SoundDisable;
Run Code Online (Sandbox Code Playgroud)

因为图像是用一个定义的x:Name.

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

Syn*_*der 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;
Run Code Online (Sandbox Code Playgroud)