Search code examples
c#wpfxamluser-controlsexpression-blend

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?


Solution

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