wpf - 尝试向按钮添加触发器以更改按钮的 Content 属性

标签 wpf triggers

我有一个用户控件,上面有一个按钮。 UserControl 有一个名为 IsNew 的 DependencyProperty。这是一个 bool 值,如果控件中正在编辑的对象是新创建的并且尚未写入数据库,则该值设置为 true。否则为假。

我有一个当前显示为“保存”的按钮。我被要求更改按钮,如果该行是新的,它会显示“插入”。我现在有下面的 XAML 按钮:

<Button Background="{DynamicResource ButtonBackground}" 
        Click="SaveButton_Click" 
        Content="Save" 
        FontSize="20" 
        FontWeight="Bold" 
        Foreground="{DynamicResource ButtonForeground}" 
        Height="60"
        IsEnabled="{Binding Path=IsDirty, RelativeSource={RelativeSource AncestorType={x:Type cs:Editor}}}"
        Margin="5"
        Name="SaveButton" 
        TabIndex="7"
        Visibility="{Binding Path=CanModify, Converter={StaticResource BoolToVisibility}}">
    <Button.Triggers>
        <Trigger Property="Editor.IsNew" Value="True">
            <Setter Property="Button.Content" Value="Insert" />
        </Trigger>
        <Trigger Property="Editor.IsNew>
            <Setter Property="Button.Content" Value="Save" />
        </Trigger>
    </Button.Triggers>
</Button>

我在运行时遇到异常,其内部异常为:
Triggers collection members must be of type EventTrigger.

我怎样才能让它工作?我可以在代码隐藏中轻松做到这一点,但我想在 XAML 中做到这一点。

谢谢

托尼

最佳答案

您只能在 Control.Triggers 中使用 EventTriggers。要使用其他类型的触发器(触发器、数据触发器),您应该使用样式:

<Button.Style>
  <Style TargetType="Button">
    <Style.Triggers>
      <Trigger Property="Editor.IsNew" Value="True">
        <Setter Property="Button.Content" Value="Insert" />
      </Trigger>

还有你的Property="Editor.IsNew"Property="Button.Content"将不起作用,因为触发器属于 Button,并且触发器将尝试在按钮上查找属性“Editor.IsNew”。您可以通过将触发器更改为 DataTrigger 并将 RelativeSource 绑定(bind)到您的 UserControl 及其 IsNew 属性来修复它。和Property="Button.Content "需要更改为 Property="Content"

关于wpf - 尝试向按钮添加触发器以更改按钮的 Content 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9789961/

相关文章:

c# - 如何在 WPF C# 中获取 treeviewitem 的级别?

c# - 在 Windows 启动时启动 wpf 应用程序

mysql - 我是否需要使用一个命令在 MySQL 触发器中开始结束?

postgresql - 当表a中的列更新时用于更新表b的Postgres函数

PHP MySQL 触发器 - 如何将变量传递给触发器?

wpf - 如何在 WPF 中有效地将文本流式传输到屏幕?

wpf - 鼠标滚轮增量值始终为 120

wpf - 使用 MVVM 绑定(bind) ListBox CheckBox IsChecked

mysql - SQL 触发器 - 使用 sum(tableB.col) WHERE tableA.userID = tableB.userID 更新表 A

google-apps-script - 除非使用脚本编辑器运行,否则不会在 Google 表格上打开侧边栏