将图像添加到wpf中的标签?
我目前正在使用WPF在C#中开发一个应用程序。 我需要做的是在标签上使它们成为标签文本左侧的图像,X的小图像或刻度的小图像,具体取决于具体情况。 我将项目中包含的图像放在名为images的文件夹中。
如何在代码中以编程方式分配要放置在标签左侧的图像,而不使用XAML代码。
因为你想要在代码背后而不是在XAML中,我建议放弃Label
并使用StackPanel
和Image
和TextBlock
,如下所示, MyGrid
可以是任何容器……
…然后在你的代码背后……
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);
您可以将其分组到网格中:
或者,由于标签是内容控件,您只需将图像控件放在标签控件中:
一旦你知道xaml应该是什么样子,通过代码创建相同的元素是非常容易的。
我不同意这里的其他两个答案。 不需要添加网格来包装内容。 stackpanel就足够了。
在xaml中,将stackpanel添加到您需要内容的位置。
然后在后面的代码中,就像在按钮处理程序中或窗口加载时添加这个
Image coolPic = new Image() { Name="pic", Source = new BitmapImage(new Uri("pack://application:,,,/images/cool.png")), Stretch = Stretch.None // this preserves the original size, fill would fill }; TextBlock text = new TextBlock() { Name = "myText", Text = "This is my cool Pic" }; myStack.Children.Add(coolPic); // adding the pic first places it on the left myStack.Children.Add(text); // the text would show up to the right
您可以通过首先添加文本然后添加图像来交换图像的位置和文本。
如果您没有看到图像,请确保图像的属性窗口中的图像构建操作设置为资源。
为了使代码更有用或更动态,您需要一种方法来更改文本或图像。
所以,让我们说你确实想要改变那些,你继续做一个
((TextBlock)FindName("myText")).Text = "my other cool pic";
你会期望文本被改变,但会发生什么?
Object reference not set to an instance of an object.
但是我给了它一个名字。 你需要添加
// register the new control RegisterName(text.Name, text);
这样您以后就可以访问文本块了。 这是必需的,因为您在构建和显示框架后将控件添加到框架中。 因此,在注册图像后,最终代码看起来像这样
Image coolPic = new Image() { Name="pic", Source = new BitmapImage(new Uri("pack://application:,,,/images/cool.png")), Stretch = Stretch.None // this preserves the original size, fill would fill }; // register the new control RegisterName(coolPic.Name, coolPic); TextBlock text = new TextBlock() { Name = "myText", Text = "This is my cool Pic" }; // register the new control RegisterName(text.Name, text); myStack.Children.Add(coolPic); myStack.Children.Add(text);