Question

The datatrigger below is not working. Any idea why not?
I checked in code behind that the LineCount in two situations is 1 respectively 4.
But when I change the Value to "-1" the trigger is working.
So why is the LineCount always -1?

<TextBox x:Name="TextInfo" TextWrapping="Wrap" Text="Information" HorizontalAlignment="Stretch" Foreground="OrangeRed">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding LineCount, ElementName=TextInfo}" Value="4">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>
                <DataTrigger Binding="{Binding LineCount, ElementName=TextInfo}" Value="1">
                    <Setter Property="Background" Value="PowderBlue" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
Was it helpful?

Solution 2

A quick decompile of the TextBox code shows that LineCount is not a DependencyProperty. So when the value is updated it will not update your trigger.

This is LineCount property from the System.Windows.Controls.TextBox class in C#. You can see here that there is not DependencyProperty backing the property.

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int LineCount
{
  get
  {
    if (this.RenderScope == null)
      return -1;
    else
      return this.GetLineIndexFromCharacterIndex(this.TextContainer.SymbolCount) + 1;
  }
}

The answer to this question as a decent solution for creating an attached property that will observe when the text in the TextBox is modified, and give the current line position. You can change your binding to listen for the attached property.

OTHER TIPS

Looking at the TextBox.LineCount Property page on MSDN, we can see that it is not a DependencyProperty. Furthermore, as the TextBox class does not implement the INotifyPropertyChanged interface, I can only imagine that the value of this property will never update for you in a Binding and can only be used in code.

The only way that I can see you using this property is if you create an Attached Property to access it and expose the updated value.

You dont need ElementName, use RelativeSource:

<DataTrigger Binding="{Binding LineCount, RelativeSource={RelativeSource Self}}" Value="4">

The LineCount property of a TextBox can be used to retrieve the current number of lines of text in a TextBox. If the text wraps to multiple lines, this property will reflect the visible number of wrapped lines that the user sees.

<TextBox x:Name="TextInfo" Text="Information" HorizontalAlignment="Stretch" Foreground="OrangeRed" **TextWrapping="Wrap"**>
    <TextBox.Style>
     ....
    </TextBox.Style>
</TextBox>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top