简体   繁体   中英

WPF User control editable property

This is my UserControl created in Blend:

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

Now I want TextBlock text property to be editable so i can change it in c# code behind.

How to do that?

Simply give the TextBlock a name using the x:Name = "myTextBlock"

then in code behind you can use myTextBlock.Text = "some other 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>

If you need to modify it outside of the class you can use the x:FieldModifier to make it public as well so that any outside class can modify it.

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

In order to edit the TextBlock in the code behind you need to give it a name by which you can access it.

<TextBlock Name="_textBox" ...

Now in the code behind you can access it by the name _textBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM