【问题标题】:`...is not a DependencyProperty` when using dependency properties and style triggers`...不是 DependencyProperty` 使用依赖属性和样式触发器时
【发布时间】:2016-03-04 12:07:36
【问题描述】:

在我的用户控件中:

public ODIF.DeviceChannel Channel
{
    get { return (ODIF.DeviceChannel)GetValue(ChannelDP); }
    set { SetValue(ChannelDP, value); }
} 

public static readonly DependencyProperty ChannelDP = DependencyProperty.Register(
    "ChannelProperty", 
    typeof(ODIF.DeviceChannel),
    typeof(ChannelBox), 
    new PropertyMetadata(new ODIF.DeviceChannel()));

然后当尝试在 XAML 中使用我的控件并使用数据触发器绑定到 Channel 时:

<local:ChannelBox VerticalAlignment="Top" HorizontalAlignment="Left" Width="200">
    <local:ChannelBox.Resources>
        <local:TypeOfConverter x:Key="TypeOfConverter"/>
    </local:ChannelBox.Resources>
    <local:ChannelBox.Style>
        <Style TargetType="{x:Type local:ChannelBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding mappingConnector, Converter={StaticResource TypeOfConverter}}" Value="{x:Type ODIF:MappingConnector}">
                    <Setter Property="Channel" Value="{Binding mappingConnector.plugin}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding mappingConnector, Converter={StaticResource TypeOfConverter}}" Value="{x:Type ODIF:InitialMappingConnector}">
                    <Setter Property="Channel" Value="{Binding mappingConnector.SourceChannel}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </local:ChannelBox.Style>
</local:ChannelBox>

在 XAML 中引发以下错误:

属性“Channel”不是 DependencyProperty。用于 标记,非附加属性必须在目标类型上公开 具有可访问的实例属性“Channel”。对于附加 属性,声明类型必须提供静态“GetChannel”和 “设置频道” 方法。

但与错误让我相信的相反(我以某种方式设置了错误的 DP),以下似乎工作正常:

<local:ChannelBox VerticalAlignment="Top" HorizontalAlignment="Left" Width="200" Channel="{Binding mappingConnector.plugin}">

这意味着它似乎只在 DP 中作为 Setter 属性在 DataTrigger 中使用时出现问题...

【问题讨论】:

    标签: c# wpf xaml dependency-properties


    【解决方案1】:

    尝试将您的静态属性命名为 ChannelProperty 而不是 ChannelDP。

    【讨论】:

    • 哦,看在皮特斯的份上,哈哈,我混淆了在哪里应用 xxxProperty 命名约定...
    • 现在它会抛出设计时错误:Item has already been added. Key in dictionary: 'InstantiatedElementViewNode' Key being added: 'InstantiatedElementViewNode
    • There are no context policies. : System.Windows.Markup.XamlParseException: 'Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.' Line number '12' and line position '18'. ---&gt; System.InvalidOperationException: Cannot re-initialize ResourceDictionary instance.
    • 这看起来无关紧要,根据经验我会说如果没有适当的上下文很难诊断。 :)
    • 我把那个归咎于 VS 脾气暴躁,我复制、删除、然后重新粘贴了我所有的资源,它神奇地起作用了....
    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 2015-08-24
    • 2012-01-31
    • 2019-12-21
    • 2021-11-08
    • 2021-12-09
    • 2019-03-14
    • 2016-11-29
    相关资源
    最近更新 更多