2

在我阅读 WPF 期间,我遇到了一个问题,试图在模板中的触发器上创建绑定,用于创建图像按钮。

<ControlTemplate x:Key="ToolbarButtonHover" TargetType="Button">
    <Grid Name="backgroundGrid">
        <Image Source="{DynamicResource ResourceKey=Img}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"></Image>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsPressed" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="#007ACC" />
        </Trigger>
        <!--Error: The property 'Binding' was not found in type Trigger-->
        <Trigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

导致 Error The property 'Binding' was not found in type Trigger,更具体地说是 <Trigger Binding="{ Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">生成它的行。

这个错误的原因是什么?

4

1 回答 1

10

可能是因为 Trigger 类上没有 Binding 属性,正如您在此处看到的那样。

您可能正在寻找DataTrigger

<ControlTemplate x:Key="ToolbarButtonHover" TargetType="Button">
    <Grid Name="backgroundGrid">
        <Image Source="{DynamicResource ResourceKey=Img}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"></Image>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsPressed" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="#007ACC" />
        </Trigger>
        <!--Look below, DataTrigger -->
        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
于 2013-09-22T21:59:36.400 回答