【问题标题】:WPF Custom Attached Property in DataTriggerDataTrigger 中的 WPF 自定义附加属性
【发布时间】:2010-08-18 16:26:04
【问题描述】:

我在 SO 上查看了类似的问题,但无法找到解决方案,所以这是我的交易:

** 我有以下课程:**

public static class ControlSecurity
{
    public static readonly DependencyProperty IsSecuredProperty =
        DependencyProperty.RegisterAttached(
            "IsSecured",
            typeof (bool),
            typeof (FrameworkElement),
            new PropertyMetadata(false));

    [AttachedPropertyBrowsableForType(typeof(Control))]
    public static bool GetIsSecured(FrameworkElement ctl)
    {
        return (bool)ctl.GetValue(IsSecuredProperty);
    }

    public static void SetIsSecured(FrameworkElement ctl, bool value)
    {
        ctl.SetValue(IsSecuredProperty, value);
    }
}

您可以推测,它会将Security:ControlSecurity.IsSecured 添加到所有FrameworkElements。

注意:Security: 指向所有这些类所在的命名空间(包括ControlSecurity

所以我已经为我的一个控件实现了这个数据模板和样式:

       <DataTemplate x:Key="SecureButtonTemplate">
            <StackPanel Orientation="Horizontal">
                <Image x:Name="SecureIcon" Source="pack://application:,,,/Resources/Icons/secure.png" Width="16" Height="16" Visibility="Collapsed" />
                <ContentPresenter Content="{Binding}" />
            </StackPanel>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured}" Value="true">
                    <Setter TargetName="SecureIcon" Property="Visibility" Value="Visible" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
        <Style TargetType="{x:Type Button}">
            <Setter Property="ContentTemplate" Value="{StaticResource SecureButtonTemplate}" />
        </Style>

这里的问题在于DataTrigger上的绑定:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured}

想法是,我想找到父按钮,并绑定到我定义的Security:ControlSecurity.IsSecured 附加属性。

我在这个绑定上尝试了大约 10 种不同的变体,但我不断收到类似这样的绑定错误:

System.Windows.Data 错误:40:BindingExpression 路径错误:在 'object' ''Button' (Name='')' 上找不到 'Security:ControlSecurity' 属性。 BindingExpression:Path=Security:ControlSecurity.IsSecured;数据项='按钮'(名称='');目标元素是'ContentPresenter'(名称='');目标属性是“NoTarget”(类型“对象”)

在这一点上我很困惑,并且希望从 WPF 专家那里获得一些见解。

【问题讨论】:

    标签: .net wpf data-binding attached-properties


    【解决方案1】:

    只需添加括号:

    Path=(Security:ControlSecurity.IsSecured)
    

    【讨论】:

    • 好吧,我做到了,现在我得到一个 XAML Parse 异常,内部异常说明:属性路径无效。 “ControlSecurity”没有名为“IsSecured”的公共属性。
    • 忽略我上面的评论,我想出了一个问题,在我的附加财产中定义了错误的所有者。
    • 甜蜜的宗教,这让我很头疼。谢谢
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2016-10-28
    • 2011-06-15
    • 2010-09-08
    相关资源
    最近更新 更多