【问题标题】:WPF: Why can't I read an attached property from inside a control-template trigger?WPF:为什么我不能从控件模板触发器中读取附加属性?
【发布时间】:2017-09-22 08:16:59
【问题描述】:

在 WPF 中,我为按钮创建了一个 ControlTemplate,并尝试通过触发器更改背景画笔。为了存储画笔的值,我使用了一个附加属性。

我测试了附加的属性本身,它运行良好 - 它可以设置,并且可以绑定到(例如当我简单地将背景绑定到该属性时)。

但是当我尝试在触发器中获取该属性(将背景更改为该属性的值)时,甚至没有读取该值(正如我在附加属性 getter 中看到断点时看到的那样),并且背景更改为透明。

我该如何解决这个问题?

<ControlTemplate x:Key="DefaultButtonTemplate"  TargetType="{x:Type Button}">
    <Border 
        x:Name="border" 
        BorderBrush="{TemplateBinding BorderBrush}" 
        BorderThickness="{TemplateBinding BorderThickness}" 
        Background="{TemplateBinding Background}" 
        SnapsToDevicePixels="True"
        >
        <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" TargetName="border" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ButtonAttachedProperties.BackgroundOnMouseOver}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

【问题讨论】:

    标签: wpf attached-properties


    【解决方案1】:

    它误解了你。它认为您引用的是属性的属性,而不是一个属性的两部分名称。尝试使用括号消除歧义,如下所示:

    Path=(myns:ButtonAttachedProperties.BackgroundOnMouseOver)
    

    不要忘记命名空间。

    【讨论】:

    • 太棒了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多