【问题标题】:WPF Custom attached property that can be emptyWPF 可以为空的自定义附加属性
【发布时间】:2016-03-25 13:59:05
【问题描述】:

我需要创建一个可以为空的自定义附加属性,如下所示:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <l:SimpleAttach.MyProperty></l:SimpleAttach.MyProperty>

</Grid>

我试过这样做:

public static class SimpleAttach
{
    public static object GetMyProperty(DependencyObject obj)
    {
        return obj.GetValue(MyPropertyProperty);
    }

    public static void SetMyProperty(DependencyObject obj, object value)
    {
        obj.SetValue(MyPropertyProperty, value);
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(object), typeof(SimpleAttach), new PropertyMetadata(null));
}

但这只会报错:

属性“MyProperty”不能为空。

相比之下,MS 创建空的附加属性似乎没有任何问题。这是一个没有给出关于为空的错误的示例:

    <TextBlock Name="VatAmount" Text="hello world" TextAlignment="Right" Margin="0,0,20,111" HorizontalAlignment="Right" Width="120" Height="16" VerticalAlignment="Bottom">
        <i:Interaction.Behaviors>
        </i:Interaction.Behaviors>
    </TextBlock>

那么我要怎么做才能告诉 XAML 这个属性允许为空呢?

【问题讨论】:

  • 你的意思是&lt;l:SimpleAttach.MyProperty&gt;null&lt;/l:SimpleAttach.MyProperty&gt;
  • 我的意思是开始标签和结束标签之间应该没有任何内容。我希望实际值因此为空。回顾 Interaction.Behaviours 的例子,我认为它是一个集合,因此允许有 0 或 n 个项目。
  • 尝试将属性设置为
  • 所以稍微深入一点,看起来 i:Interaction.Behaviors 实际上是一个 BehaviorCollection。因此它的列表中可以有 0 个项目,因此在 XAML 中允许为空。

标签: wpf xaml attached-properties


【解决方案1】:

好的,所以我终于弄清楚了我的问题。有时阅读官方文档会有所帮助:XAML Syntax In Detail

特别是我似乎指的是“内容属性”。

XAML 内容语法是一种仅在将 ContentPropertyAttribute 指定为类声明的一部分的类上启用的语法。 ContentPropertyAttribute 引用作为该类型元素(包括派生类)的内容属性的属性名称。当由 XAML 处理器处理时,在对象元素的开始标记和结束标记之间找到的任何子元素或内部文本都将被分配为该对象的 XAML 内容属性的值。

其次,在微软Interactivity.Behaviors的例子中,就是一个集合,集合中允许有0个项目。

此外,如果您沿着实现附加行为(即集合)的道路前进,那么这篇文章将指导您完成这些怪癖:Attached property of type list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多