Search code examples
c#wpfxamltextblock

Cannot have both the text and the child element 'LineBreak' within a property element


I have the following XAML:

    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap" Margin="15">
        line1<LineBreak/><LineBreak/>
        line2
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Visibility" Value="Hidden"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding State}" Value="ShowText">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>

However Visual Studio throws the error

Cannot have both the text 'line1' and the child element 'LineBreak' within a property element.

And I don't know how to keep the line breaks and also fix the issue. I tried this:

    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap" Margin="15">
        <TextBlock.Text>
        line1<LineBreak/><LineBreak/>
        line2
        </TextBlock.Text>
            <TextBlock.Style>
                <Style TargetType="{x:Type TextBlock}">
                    <Setter Property="Visibility" Value="Hidden"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding State}" Value="ShowText">
                            <Setter Property="Visibility" Value="Visible"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>

But then got the repeating error "Text property set more than once".


Solution

  • Put the Inlines behind the Style:

    <TextBlock ...>
        <TextBlock.Style>
            ...
        </TextBlock.Style>
        line1<LineBreak/><LineBreak/>
        line2
    </TextBlock>