Bip
Bip

Reputation: 913

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?

Upvotes: 2

Views: 1076

Answers (2)

Dan P
Dan P

Reputation: 1999

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>

Upvotes: 4

JaredPar
JaredPar

Reputation: 755141

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

Upvotes: 2

Related Questions