WPF布尔触发器

6

我在我的WPF应用程序的Window类中有一个布尔值。如何根据这个布尔值是true还是false来触发相应的操作?

<Grid>
  <Grid.Triggers>
    <Trigger ... />
  </Grid.Triggers>
</Grid>

感谢您的选择。
2个回答

13

在*.cs文件中:

public partial class MainWindow : INotifyPropertyChanged
{
    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public bool Flag { get; set; }

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        Flag = true;
        OnPropertyChanged("Flag");
    }

    protected void OnPropertyChanged(string property)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

XAML 表单中:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">

    <Window.Resources>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Flag}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Button Click="ButtonClick" Content="Click Me" />
    </Grid>
</Window>

3
你可以使用DataTrigger。不过我认为你需要在样式或模板中使用它。
另外,你也可以在代码后台捕获变化。

这就是你的答案。你将布尔值暴露为设置为数据上下文的对象的属性,然后通过DataTrigger绑定到它。但正如注意到的那样,触发器只在样式和模板内可用。 - donovan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接