如何在不使用 XAML 的情况下将图像添加到切换按钮

本文关键字:添加 图像 按钮 情况下 XAML | 更新日期: 2023-09-27 17:55:08

我正在尝试将图像添加到WPF - C#中的切换按钮。问题是我正在处理的任务根本无法使用 XAML 进行。我尝试将 Content 属性设置为图像,但我得到的只是一个普通的切换按钮,这对我的事业根本没有帮助。

    myToggleButton = new ToggleButton();
    myImage = new Image();
    BitmapImage bmi = new BitmapImage();
    bmi.BeginInit();
    bmi.UriSource = new Uri("myImageResource.bmp", UriKind.Relative);
    bmi.EndInit();
    myImage.Source = bmi;
    myToggleButton.Content = myImage;

希望我提供了足够的信息,如果没有,请询问更多。

@Phil赖特更新:

当我像这样宣传图片时:

    myImage = new Image();
    BitmapImage bmi = new BitmapImage();
    bmi.BeginInit();
    bmi.UriSource = new Uri("myImageResource.bmp", UriKind.Relative);
    bmi.EndInit();
    myImage.Source = bmi;

它有效...

@Matt西部更新:

    myGrid.Children.add(MyToggleButton); // This gives me an empty ToggleButton
    myGrid.Children.add(MyImage); // This gives me an image with content

如何在不使用 XAML 的情况下将图像添加到切换按钮

您正在创建一个新的切换按钮,但未将其添加到任何内容中。图像正在添加到切换按钮,但实际的切换按钮不会作为子项添加到任何内容。您需要在代码后面添加切换按钮

,如下所示:
this.AddChild(myToggleButton);

或者,如果已在 XAML 中定义了名为 myToggleButton 的切换按钮,请从上面的代码中删除此行

myToggleButton = new ToggleButton();

按照要求,这里是完全适合我的代码:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="_Root">
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var tb = new ToggleButton();
            var image = new Image();
            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri("/Images/6.png", UriKind.Relative);
            bmi.EndInit();
            image.Source = bmi;
            tb.Content = image;
            _Root.Children.Add(tb);
        }
    }
}
如果图像

是资源;如前所述,最后两行没有意义,如果可以让图像自行显示,它也应该显示在按钮内。

您确定能够提供的位图资源吗?如果不是,则图像将为空,因此不占用空间,因此切换按钮看起来为空。

切换按钮的图像可以这样设置:

ToggleButton tgb = new ToggleButton();
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("myImageResource.bmp", UriKind.Relative);
bmi.EndInit();
tgb.Content = new Image { Source = bmi };