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

Ton*_*ile 4 wpf triggers

我有一个UserControl,上面有一个按钮.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>
Run Code Online (Sandbox Code Playgroud)

我在运行时遇到异常,其内部异常如下:

Triggers collection members must be of type EventTrigger.
Run Code Online (Sandbox Code Playgroud)

我如何让它工作?我可以在代码隐藏中轻松地做到这一点,但我想在XAML中做到这一点.

谢谢

托尼

Nik*_*lay 11

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

<Button.Style>
  <Style TargetType="Button">
    <Style.Triggers>
      <Trigger Property="Editor.IsNew" Value="True">
        <Setter Property="Button.Content" Value="Insert" />
      </Trigger>
Run Code Online (Sandbox Code Playgroud)

而且你Property="Editor.IsNew"Property="Button.Content"不会起作用,因为触发器是属于巴顿和触发器将尝试在按钮找物业"Editor.IsNew".您可以通过将触发器更改为DataTrigger并使用RelativeSource绑定到UserControl及其IsNew属性来修复它.并且Property="Button.Content"需要改为Property="Content".