Button 中的 DataTrigger 绑定未反映在值更改上

DataTrigger Binding in Button not reflected on value change

我有一个按钮,其可见性会根据绑定值而改变。这是我的代码

        <Button Content="Click Me" Grid.Column="1" Click="Button_Click" Width="100" Height="100">
            <Button.Style>
                <Style TargetType="Button">
                    <Setter Property="Visibility" Value="Visible"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=isShow, Mode=TwoWay}" Value="True">
                            <Setter Property="Visibility" Value="Hidden"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Path=isShow, Mode=TwoWay}" Value="False">
                            <Setter Property="Visibility" Value="Visible"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
public bool isShow { get; set; }       
private void Button_Click(object sender, RoutedEventArgs e)
{
   this.isShow = !this.isShow;
}

我是 C# 的初学者,正在习惯数据绑定。请让我知道哪里出错了。

您应该实施 INotifyPropertyChanged 并从 isShow 属性 的 setter 引发 PropertyChanged 事件,以便 Visibility 获得每当源 属性 动态设置为新值时刷新:

public class MainWindow : Window, INotifyPropertyChanged
{
    ...

    private bool _isShow;
    public bool isShow
    {
        get { return _isShow; }
        set { _isShow = value; NotifyPropertyChanged(); }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.isShow = !this.isShow;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

您还可以删除触发器之一:

<Button Content="Click Me" Grid.Column="1" Click="Button_Click" Width="100" Height="100">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Visibility" Value="Visible"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=isShow, Mode=TwoWay}" Value="True">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>