Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C代码WPF中向标签添加文本块_C#_Wpf_Xaml - Fatal编程技术网

C# 在C代码WPF中向标签添加文本块

C# 在C代码WPF中向标签添加文本块,c#,wpf,xaml,C#,Wpf,Xaml,在我的代码中,我创建了一个新标签,并对其进行格式化,使其成为堆叠面板的子标签。但是在标签的内部,我需要添加一个文本块,我很难找到如何做到这一点 仅使用代码,我需要创建由代码创建的WPF,以便像这样工作: <Label Background="#000000" Foreground="#FFFFFF"> <TextBlock TextWrapping="Wrap" Text="Text Here"/> </Label> 但是,当我使用它将新标签添加到S

在我的代码中,我创建了一个新标签,并对其进行格式化,使其成为堆叠面板的子标签。但是在标签的内部,我需要添加一个文本块,我很难找到如何做到这一点

仅使用代码,我需要创建由代码创建的WPF,以便像这样工作:

<Label Background="#000000" Foreground="#FFFFFF">
    <TextBlock TextWrapping="Wrap" Text="Text Here"/>
</Label>
但是,当我使用它将新标签添加到StackedPanel时,它就起作用了


我之所以需要这样做,是因为我需要在标签中包装文本,但不能仅使用TextBlock或其他控件。

只需将TextBlock设置为标签的内容即可满足您的要求

Label lbl = new Label ();
TextBlock txtBlock = new TextBlock ();
txtBlock.TextWrapping = TextWrapping.Wrap;
lbl.Content = txtBlock;

您还可以向资源中添加一个“标签”样式,其中包含字符串类型的默认数据模板。因此,任何标签中的所有字符串内容都被包装

<Application.Resources>
    <Style TargetType="Label">
        <Style.Resources>
            <DataTemplate xmlns:sys="clr-namespace:System;assembly=mscorlib" DataType="{x:Type sys:String}">
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Style.Resources>
    </Style>
</Application.Resources>
<Application.Resources>
    <Style TargetType="Label">
        <Style.Resources>
            <DataTemplate xmlns:sys="clr-namespace:System;assembly=mscorlib" DataType="{x:Type sys:String}">
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Style.Resources>
    </Style>
</Application.Resources>
<Label Content="A very long string for my Label" />
var Label = new Label { Content = "A very long string for my Label" }