无法在Setter中设置附加属性



我在自定义控件中有一个Style,我试图在其中设置Label上的附加属性。

风格

<Style x:Key="DayNumberStyle" TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Setter Property="local:DateRangePickerHelper.SelectionType" Value="Selected"></Setter>
</Style>

附加属性

public class DateRangePickerHelper : FrameworkElement
{
public static readonly DependencyProperty SelectionTypeProperty = DependencyProperty.RegisterAttached(
"DateSelectionType", typeof(DateSelectionType), typeof(DateRangePickerHelper),
new PropertyMetadata(DateSelectionType.NotSelected));
public static void SetSelectionType(DependencyObject element, DateSelectionType value)
{
element.SetValue(SelectionTypeProperty, value);
}
public static DateSelectionType GetSelectionType(DependencyObject element)
{
return (DateSelectionType)element.GetValue(SelectionTypeProperty);
}
}

枚举

public enum DateSelectionType
{
NotSelected,
Selected,
StartDate,
EndDate
}

标签

<Label Style="{StaticResource DayNumberStyle}" Grid.Column="0" Content="{Binding Sunday}">
<b:Interaction.Triggers>                                                                                
<b:EventTrigger EventName="MouseLeftButtonUp">                                                                                    
<b:InvokeCommandAction Command="{Binding Path=LabelClickedCommand, RelativeSource={RelativeSource AncestorType=local:DateRangePicker}}"                                                                                            CommandParameter="{Binding Sunday}"></b:InvokeCommandAction>                                                                                
</b:EventTrigger>                                                                            
</b:Interaction.Triggers>
</Label>

错误

值不能为null。(参数"property"(

当我从Setter中删除附加的属性时,一切正常。

有人能解释一下为什么我不能用StyleSetter设置这个吗?

您定义了一个依赖属性SelectionTypeProperty,因此它的名称必须是SelectionType,正如您在文档中所读到的:如何实现依赖属性(WPF.NET(

标识符字段必须遵循命名约定<property name>Property。例如,如果使用名称Location注册依赖项属性,则标识符字段应命名为LocationProperty

但是,在您的定义中,您传递DateSelectionType名称,这是属性的类型的名称,而不是属性本身的name。

如果您未能遵循此命名模式,则WPF设计器可能无法正确报告您的属性,并且属性系统样式应用程序的方面可能无法按预期运行

将名称更改为SelectionType,即可正常工作。

public static readonly DependencyProperty SelectionTypeProperty = DependencyProperty.RegisterAttached(
"SelectionType", typeof(DateSelectionType), typeof(DateRangePickerHelper),
new PropertyMetadata(DateSelectionType.NotSelected));

如果您实现了一个具有属性包装器而不是方法的常规依赖属性,则可以使用nameof(<YourProperty>)来防止这种情况和重命名问题。

最新更新