【问题标题】:WPF: binding a static resource to a dependency property in a user controlWPF:将静态资源绑定到用户控件中的依赖属性
【发布时间】:2018-03-03 01:56:37
【问题描述】:

我有一个用户控件,它是一个图标容器。

<Rectangle x:Name="Rectangle"
           Width="{Binding SquareWidth}"
           Height="{Binding SquareWidth}"
           Fill="{Binding FillBrush}"
           DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}, Mode=OneWay}">
    <Rectangle.OpacityMask>
        <VisualBrush Visual="{Binding VisualItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Stretch="UniformToFill" />
    </Rectangle.OpacityMask>
</Rectangle>

在代码隐藏中:

    public static readonly DependencyProperty CanvasItemDependencyProperty =
        DependencyProperty.Register(nameof(VisualItem), typeof(Canvas),
            typeof(SquareIcon), new FrameworkPropertyMetadata());

    public Canvas VisualItem
    {
        get => GetValue(CanvasItemDependencyProperty) as Canvas;
        set => SetValue(CanvasItemDependencyProperty, value);
    }

图标绘图被定义为资源字典中的 Canvas 项:

<Canvas x:Key="appbar_3d_3ds" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
    <Path Width="32" Height="40" Canvas.Left="23" Canvas.Top="18" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 27,18L 23,26L 33,30L 24,38L 33,46L 23,50L 27,58L 45,58L 55,38L 45,18L 27,18 Z "/>
</Canvas>

我在主窗体中实例化我的用户控件,如下所示:

<controls:SquareIcon VisualItem="{StaticResource appbar_information_circle}" Width="16" Height="16" FillBrush="Black" SquareWidth="16" Margin="0,0,5,0"/>

但我得到的只是一个透明的正方形。

如果我将“Binding VisualItem”替换为“StaticResource appbar_information_circle”,则会显示图标。

我错过了什么?

【问题讨论】:

    标签: wpf data-binding dependency-properties staticresource


    【解决方案1】:

    您没有遵循依赖属性的强制性命名约定。名为 VisualItem 的依赖属性的标识符字段必须命名为 VisualItemProperty,否则 XAML 解析器无法解析它。

    public static readonly DependencyProperty VisualItemProperty =
        DependencyProperty.Register(
            nameof(VisualItem), typeof(Canvas), typeof(SquareIcon));
    
    public Canvas VisualItem
    {
        get => (Canvas)GetValue(VisualItemProperty)
        set => SetValue(VisualItemProperty, value);
    }
    

    在属性 getter 中使用 as 运算符没有用处,因为属性值始终是 Canvas。如果不是(这是一个编程错误),您将希望获得 InvalidCastException 而不是 NullReferenceException。

    您还应该考虑将依赖属性的类型从 Canvas 更改为 Visual。它的工作方式相同,但在可以将哪些元素分配给属性方面提供了更大的灵活性。


    请注意,在 Visual Binding 上设置 Mode=TwoWayUpdateSourceTrigger=PropertyChanged 是没有意义的。绑定应该是这样的:

    <VisualBrush Visual="{Binding VisualItem}" .../>
    

    【讨论】:

    • 感谢您指出我的愚蠢错误!问题解决了。我不知道这个神奇的命名约定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2023-03-26
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多