0
votes

I'm struggeling with binding a datatrigger to a textblock property. I have added a working Datatrigger example in the TextBox. The issue is the TextBlock DataTrigger I can not get working. At startup IsNameActive has value 'false' and BackGround is PaleVioletRed, but it does not change when IsNameActive changes.

   public bool IsNameActive
    {
        get => !string.IsNullOrEmpty(FirstName);
    }


    public string FirstName
    {
        get => _firstName;
        set
        {
            if (value != _firstName)
            {
                _firstName = value;
                OnPropertyChanged(FirstName);
                OnPropertyChanged(IsNameActive);
            }
        }
    }

   <TextBox
        Grid.Row="0"
        Grid.Column="1"
        Margin="15"
        Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=FirstName, ValidatesOnDataErrors=true, NotifyOnValidationError=true}">
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Setter Property="Background" Value="RosyBrown" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="aa">
                        <Setter Property="Background" Value="DarkOliveGreen" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="">
                        <Setter Property="Background" Value="CornflowerBlue" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>



    <TextBlock
        Grid.Row="2"
        Grid.Column="1"
        Margin="15"
        Text="TextBlock with binding">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=DataContext.IsNameActive, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}" Value="true">
                        <Setter Property="Background" Value="CornflowerBlue" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=DataContext.IsNameActive, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}" Value="false">
                        <Setter Property="Background" Value="PaleVioletRed" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
1
I don't think OnPropertyChanged(IsNameActive); passes correct property name. you probably need OnPropertyChanged(nameof(IsNameActive));ASh
Thank you, that fixed it!Cecilie

1 Answers

0
votes

As @Ash pointed out in the comment section, you need to wrap nameof around IsNameActive when you call OnPropertyChanged:

OnPropertyChanged(nameof(IsNameActive));