Search code examples
wpfdatatrigger

WPF datatrigger not firing


I'm trying to change the background colour of a text box in WPF based on its content.

Using breakpoints, I see my ValueConverter gets constructed, but neither Convert nor ConvertBack methods ever get called, and so the styling doesn't work.

The 'LightBlue' style in the XAML does work at startup.

I tried to use Snoop but I don't know what I'm looking for.

XAML...

    <Grid.Resources>
        <local:ThreadCreationLimitChanged x:Key="ThreadCreationLimitChanged"></local:ThreadCreationLimitChanged>
    </Grid.Resources>
    <Label Grid.Row="0" Grid.Column="0" Margin="0, 5, 0, 0" Content="New Thread Limit"></Label>
    <TextBox Grid.Row="0" Grid.Column="1" Margin="10, 5, 10, 0" Width="100" Text="{Binding Path=ManagerConfig.ThreadCreationLimit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
        <TextBox.Style>
            <Style>
                <Setter Property="TextBox.Background" Value="LightBlue"></Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Text,Converter={StaticResource ThreadCreationLimitChanged}}" Value="false">
                        <Setter Property="TextBox.Background" Value="Yellow"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

ValueConverter...

public class ThreadCreationLimitChanged : IValueConverter
{
    public ThreadCreationLimitChanged()
    {
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString() == "120";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

A bit of class ManagerConfig... (NotifyPropertyChanged implements INotifyPropertyChanged)

class ManagerConfig : NotifyPropertyChanged
{
    private uint _ThreadCreationLimit;

    public uint ThreadCreationLimit
    {
        get { return _ThreadCreationLimit; }
        set
        {
            _ThreadCreationLimit = value;
            OnPropertyChanged("ThreadCreationLimit");
        }
    }

Solution

  • Change this {Binding Path=Text,Converter={StaticResource ThreadCreationLimitChanged}} to {Binding Path=Text, RelativeSource={RelativeSource Self} ,Converter={StaticResource ThreadCreationLimitChanged}}