无法在Setter中设置WPF附加属性,求问题原因
问题:无法通过Style的Setter设置自定义附加属性?
在自定义控件的Style中尝试为Label设置附加属性,移除Setter中的附加属性后程序运行正常,但添加后抛出错误,请问原因是什么?
样式代码
<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代码
<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>
报错信息
Value cannot be null. (Parameter 'property')
原因分析
核心问题是附加属性注册名称与Setter引用名称不匹配,违反了WPF附加属性的命名约定:
- 附加属性注册时,
RegisterAttached方法的第一个参数是属性的公开名称,这里填的是"DateSelectionType" - 但Set/Get方法的后缀是
SelectionType,Setter里引用的也是local:DateRangePickerHelper.SelectionType - WPF会根据Setter中的属性名称,自动拼接成
GetSelectionType/SetSelectionType方法查找对应附加属性,同时要求注册的属性名必须和方法后缀一致。由于注册名与引用名不匹配,WPF无法找到对应的DependencyProperty实例,最终抛出空引用错误。
修正方案
将附加属性的注册名称改为"SelectionType",与Set/Get方法的后缀保持一致:
public class DateRangePickerHelper : FrameworkElement { // 修正注册名称为"SelectionType",与方法后缀匹配 public static readonly DependencyProperty SelectionTypeProperty = DependencyProperty.RegisterAttached( "SelectionType", 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); } }
修改后,Style中的Setter就能正确匹配到附加属性,程序可正常运行。
内容的提问来源于stack exchange,提问作者3xGuy
相关产品推荐
相关产品推荐

