WPF用户控制可编辑属性

时间:2012-03-31 15:52:32

标签: c# wpf xaml user-controls expression-blend

这是我在Blend中创建的UserControl

<StackPanel Orientation="Horizontal" Background="#FF0084FF" Height="400">
        <TextBlock TextWrapping="Wrap" Margin="10,0,20,0" Text="Kategorija1" FontFamily="Segoe Print" FontWeight="Bold" FontSize="26.667" RenderTransformOrigin="0.5,0.5" Foreground="White" TextAlignment="Center"  VerticalAlignment="Center">
            <TextBlock.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="-90"/>
                    <TranslateTransform/>
                </TransformGroup>
            </TextBlock.RenderTransform>
        </TextBlock>

现在我希望TextBlock文本属性可以编辑,这样我就可以在后面的c#代码中更改它。

怎么做?

2 个答案:

答案 0 :(得分:4)

只需使用x:Name =“myTextBlock”

为TextBlock命名

然后在代码后面你可以使用myTextBlock.Text =“其他一些文本”

<StackPanel Orientation="Horizontal" Background="#FF0084FF" Height="400">
    <TextBlock x:Name = "myTextBlock" TextWrapping="Wrap" Margin="10,0,20,0" Text="Kategorija1" FontFamily="Segoe Print" FontWeight="Bold" FontSize="26.667" RenderTransformOrigin="0.5,0.5" Foreground="White" TextAlignment="Center"  VerticalAlignment="Center">
        <TextBlock.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="-90"/>
                <TranslateTransform/>
            </TransformGroup>
        </TextBlock.RenderTransform>
    </TextBlock>
</StackPanel>

如果你需要在类之外修改它,你可以使用x:FieldModifier使它公开,以便任何外部类都可以修改它。

<StackPanel Orientation="Horizontal" Background="#FF0084FF" Height="400">
    <TextBlock x:Name = "myTextBlock" x:FieldModifier="public" TextWrapping="Wrap" Margin="10,0,20,0" Text="Kategorija1" FontFamily="Segoe Print" FontWeight="Bold" FontSize="26.667" RenderTransformOrigin="0.5,0.5" Foreground="White" TextAlignment="Center"  VerticalAlignment="Center">
        <TextBlock.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="-90"/>
                <TranslateTransform/>
            </TransformGroup>
        </TextBlock.RenderTransform>
    </TextBlock>
</StackPanel>

答案 1 :(得分:2)

要编辑后面代码中的TextBlock,您需要为其命名,以便您可以访问它。

<TextBlock Name="_textBox" ...

现在在后面的代码中,您可以通过名称_textBox

访问它