如何将图像和文本块添加到 WPF ContentControl

How to add an Image and a Textblock into a WPF ContentControl

我在 WPF 中有一个 ContentControl,里面有一个图像

ContentControl myContentControl = new ContentControl();
myContentControl.Content = image;

如何在 ContentControl 中的图像旁边添加文本块? 谢谢。

contentControl的属性 ContentTemplate需要改成ContentTemplate,这里解释一下:

Gets or sets the data template used to display the content of the ContentControl.

您还需要创建一个 class 来表示您的数据,如下所示:

public class ImageInfo
{
    public string Caption { get; set; }
    public ImageSource Image { get; set; }
}

最好在XAML中创建ContentControl,像这样:

    <ContentControl x:Name="cc">
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <StackPanel>
                    <Image Source="{Binding Image}" />
                    <TextBlock Text="{Binding Caption}" />
                </StackPanel>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>

然后,将数据分配给 ContentControl:

cc.Content = new ImageInfo() { Caption = "Hello", Image = new BitmapImage(new System.Uri("/Assets/User.jpg", UriKind.Relative)) };

你做的事情看起来你不熟悉MVVM: 请检查 here

简单的解决方案

但是如果你想要丑陋的解决方案并在你的代码后面创建 UIElements - 像这样:

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

    }