1

我正在尝试将图像添加到 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 Wright:

当我为这样的图片做广告时:

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

有用...

更新@Matt West:

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

4 回答 4

1

您正在创建一个新的切换按钮,但您没有将其添加到任何内容中。图像被添加到切换按钮中,但实际的切换按钮并未作为子项添加到任何内容中。您需要在后面的代码中添加切换按钮,如下所示:

this.AddChild(myToggleButton);

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

myToggleButton = new ToggleButton();
于 2011-05-07T17:26:17.067 回答
1

正如这里所要求的,代码完全适用于我:

<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);
        }
    }
}

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

于 2011-05-09T09:14:35.860 回答
0

您确定可以找到提供的位图资源吗?如果不是,那么图像将是空的,因此不占用空间,因此切换按钮看起来是空的。

于 2011-05-07T10:42:41.683 回答
0

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

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 };
于 2011-05-11T21:42:13.840 回答