Mrg Gek
Mrg Gek

Reputation: 936

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

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>

Upvotes: 1

Views: 2190

Answers (1)

mm8
mm8

Reputation: 169400

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.

Upvotes: 1

Related Questions