How do I set DataTrigger to the TextBox "Text" Property?

1.9k views Asked by At

How do I set DataTrigger to the TextBox "Text" Property? I don't want to set DataTrigger to the Property which my TextBox "Text" Property is bind to.

I have a Style for the TextBox. This DataTrigger doesn't work and I don't know why.

<Style x:Key="DatagridTextboxStyle" TargetType="TextBox">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="0">
                <Setter Property="Text" Value="X"></Setter>
            </DataTrigger>
        </Style.Triggers>
</Style>

And this is my TextBox which is a Tempate for the DatagridCell's

<DataGridTemplateColumn Header="6">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Style="{StaticResource DatagridTextboxStyle}" IsReadOnly="true" Width="{Binding ElementName=AccRecOverdueTbl, Path=ActualWidth}" Text="{Binding AccountsReceivable.OverdueAtTheEndOfTheReportingPeriod, Mode=TwoWay}"></TextBox>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
1

There are 1 answers

0
mm8 On

This doesn't work for two reasons. The first and most obvious one is that setting the same property in the setter that the DataTrigger is bound to will cause a StackOverflowException to be thrown. The Text property is set, the trigger triggers, that text is set again, the triggers fires again and so on.

The second thing is that local values take precedence over values set by style setters. So if you set the Text property of the TextBox in the CellTemplate of the DataGridColumn, a Style setter won't ever be able to "override" this value.

You could instead use a converter that returns "X" when the OverdueAtTheEndOfTheReportingPeriod source property returns 0. Or you could add another source property to the class that returns a string and bind to this one directly:

public string FormattedOverdueAtTheEndOfTheReportingPeriod
{
  get { return OverdueAtTheEndOfTheReportingPeriod == 0 ? "X" : OverdueAtTheEndOfTheReportingPeriod.ToString(); }
}

Using a DataTrigger is not an option.