Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.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# 如何以编程方式将TextBlock添加到WPF样式?_C#_Wpf_Xaml - Fatal编程技术网

C# 如何以编程方式将TextBlock添加到WPF样式?

C# 如何以编程方式将TextBlock添加到WPF样式?,c#,wpf,xaml,C#,Wpf,Xaml,我有一个自定义控件的WPF样式。样式如下所示: <Style x:Key="MyStyle" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid x:Name="Lay

我有一个自定义控件的WPF样式。样式如下所示:

<Style x:Key="MyStyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="LayoutRoot">

                        <Rectangle x:Name="background" Width="450" Height="450" RadiusX="3" RadiusY="3" Fill="White" />
                        <TextBlock Name="MyText" Foreground="Black" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="5" FontSize="52" Text="Text"/>

                        <ContentPresenter x:Name="content" />
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="background" Property="Fill" Value="Red" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>

现在如何以编程方式添加TextBlock,使其样式与以前的样式相匹配?

您可以将其作为内容的一部分,并在中显示出来ContentPresenter@ASh你能提供如何做到这一点的代码吗?我对WPF不是很了解。如果这只是为了设置文本,为什么不将文本绑定到控件的另一个属性?与往常一样,使用TemplateBinding。@Clemens方法检查传递给它的文本字符串,以便文本的某些部分(不是所有文本)可以加粗、加下划线等。在本例中,它是一个常规字符串,但并不总是这样。据我所知,这需要通过编程来完成。你是说你正在为TextBlock的
内联线
集合创建元素?
//Create the TextBlock using a method I wrote myself
TextBlock MyTest = CreateTextBlock("Text", Brushes.Black, HorizontalAlignment.Left, VerticalAlignment.Bottom, 52);

//Now get the style I want to change
Style CurrentStyle = (Style)FindResource("MyStyle");

//What next?