【发布时间】: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 这个属性允许为空呢?
【问题讨论】:
-
你的意思是
<l:SimpleAttach.MyProperty>null</l:SimpleAttach.MyProperty> -
我的意思是开始标签和结束标签之间应该没有任何内容。我希望实际值因此为空。回顾 Interaction.Behaviours 的例子,我认为它是一个集合,因此允许有 0 或 n 个项目。
-
尝试将属性设置为
-
所以稍微深入一点,看起来 i:Interaction.Behaviors 实际上是一个 BehaviorCollection。因此它的列表中可以有 0 个项目,因此在 XAML 中允许为空。
标签: wpf xaml attached-properties