【问题标题】:Trying to add a trigger to a button to change the button's Content property尝试向按钮添加触发器以更改按钮的 Content 属性
【发布时间】:2012-03-20 23:51:17
【问题描述】:

我有一个用户控件,上面有一个按钮。 UserControl 有一个名为 IsNew 的 DependencyProperty。这是一个布尔值,如果控件中正在编辑的对象是新创建的并且尚未写入数据库,则该值设置为 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 中做到这一点。

谢谢

托尼

【问题讨论】:

    标签: wpf triggers


    【解决方案1】:

    您只能在 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" 也不起作用,因为触发器属于按钮,触发器会尝试在按钮上查找属性“Editor.IsNew”。您可以通过将触发器更改为 DataTrigger 并将 RelativeSource 绑定到您的 UserControl 及其 IsNew 属性来修复它。而Property="Button.Content”需要改成Property="Content"

    【讨论】:

      【解决方案2】:

      原因是控件只能实现EventTriggers。您需要的另一种触发器必须以一种样式实现,然后您的按钮使用该样式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-04-17
        • 1970-01-01
        • 2015-08-22
        相关资源
        最近更新 更多