[英]How to add an Image and a Textblock into a WPF ContentControl
I have a ContentControl in WPF,which has an image in it 我在WPF中有一个ContentControl,其中有一个图像
ContentControl myContentControl = new ContentControl();
myContentControl.Content = image;
How do I to add a textblock next to the image inside the ContentControl? 如何在ContentControl内的图像旁边添加文本块? Thank you.
谢谢。
You need to change the property ContentTemplate
of the contentControl, as to ContentTemplate
, here is some explanation: 对于
ContentTemplate
,您需要更改contentControl的属性ContentTemplate
,这是一些解释:
Gets or sets the data template used to display the content of the ContentControl.
获取或设置用于显示ContentControl内容的数据模板。
Also you need create a class to represent your data, like this: 您还需要创建一个类来表示您的数据,如下所示:
public class ImageInfo
{
public string Caption { get; set; }
public ImageSource Image { get; set; }
}
It is better to create ContentControl
in XAML, like this: 最好在XAML中创建
ContentControl
,如下所示:
<ContentControl x:Name="cc">
<ContentControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Image}" />
<TextBlock Text="{Binding Caption}" />
</StackPanel>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
Then, assign the data to the ContentControl: 然后,将数据分配给ContentControl:
cc.Content = new ImageInfo() { Caption = "Hello", Image = new BitmapImage(new System.Uri("/Assets/User.jpg", UriKind.Relative)) };
What you are doing looks like you are not familiar with MVVM
: Please check here 您正在做的事情看起来好像您不熟悉
MVVM
:请在此处检查
Easy Solution 简易解决方案
But if you want the ugly solution and create UIElement
s in your code behind - go like this: 但是,如果您想要丑陋的解决方案并在后面的代码中创建
UIElement
,请按照以下步骤操作:
public static ContentControl CreateControl(string title, Uri path)
{
//Create your image
BitmapImage bitmapImage = new BitmapImage(path);
Image image = new Image()
{
Source = bitmapImage
};
//Create your Text
TextBlock textB = new TextBlock()
{
Text = title
};
//Put them together
StackPanel content = new StackPanel();
content.Children.Add(image);
content.Children.Add(textB);
//Add this to the content control
return new ContentControl()
{
Content = content
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.