将图像添加到 wpf 中的标签? [英] adding an image to a label in wpf?

查看:45
本文介绍了将图像添加到 wpf 中的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 WPF 在 C# 中开发应用程序.我需要能够做的是在标签上使它们成为标签文本左侧的图像、X 的小图像或刻度的小图像,具体取决于具体情况.我已将项目中包含的图像放在名为 images 的文件夹中.

I am currently developing an application in C# using WPF. What I need to be able to do is on a label make their be an image to the left of the text of the label a small image of an X or a small image of a tick depending on the circumstances. I have got the images included in the project in a folder named images.

如何在代码中以编程方式而不使用 XAML 代码分配要放置在标签左侧的图像.

How can I assign the images to be placed on the left of the label programatically in the code and not using the XAML code.

推荐答案

由于您希望在代码后面而不是在 XAML 中使用它,我建议放弃 Label 并使用 StackPanel 加上 ImageTextBlock 如下所示,其中 MyGrid 可以是任何容器...

Since you want this in code behind and not within XAML I would suggest ditching the Label and using a StackPanel coupled with an Image and TextBlock as seen below where MyGrid could be any container...

        <Grid Name="MyGrid"/>

...然后在你的代码后面...

...then in your code behind...

        StackPanel myStackPanel = new StackPanel();
        myStackPanel.Orientation = Orientation.Horizontal;

        Image myImage = new Image();
        BitmapImage myImageSource = new BitmapImage(); 
        myImageSource.BeginInit();
        myImageSource.UriSource = new Uri("Images/MyImage.png");
        myImageSource.EndInit();
        myImage.Source = myImageSource;

        TextBlock myTextBlock = new TextBlock();
        myTextBlock.Text = "This is my image";

        myStackPanel.Children.Add(myImage);
        myStackPanel.Children.Add(myTextBlock);

        MyGrid.Children.Add(myStackPanel);

这篇关于将图像添加到 wpf 中的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆