文本块中的wpf datatrigger绑定datacontext不起作用

时间:2018-05-25 07:59:00

标签: wpf binding datatrigger

我正在将数据触发器绑定到textblock属性。我在TextBox中添加了一个有效的Datatrigger示例。 问题是TextBlock DataTrigger我无法正常工作。在启动时IsNameActive有价值' false'和BackGround是PaleVioletRed,但是当IsNameActive改变时它不会改变。

   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 个答案:

答案 0 :(得分:0)

正如@Ash在评论部分指出的那样,当你致电nameof时,你需要在IsNameActive附近OnPropertyChanged包裹:

OnPropertyChanged(nameof(IsNameActive));