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

问题描述 投票:0回答:1

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

        <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#的初学者,已经习惯了数据绑定。请让我知道我哪里出错了。

c# wpf data-binding datatrigger
1个回答
0
投票

您应该实现INotifyPropertyChanged并从PropertyChanged属性的设置器中引发isShow事件,以便Visibility每当将source属性动态设置为新值时都可以刷新:

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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.