无法使用嵌套的依赖项属性初始化UserControl

时间:2016-09-28 16:37:35

标签: wpf user-controls dependency-properties

我正在尝试公开嵌套控件的两个依赖项属性。在这种情况下DisplayFormatString<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" xmlns:local="clr-namespace:View.UserControls" xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core" x:Class="View.UserControls.DateTimeEdit" mc:Ignorable="d" > <Grid> <dxe:DateEdit x:Name="localDateEdit" Width="200" MaskType="DateTime" ShowEditorButtons="True" Mask ="dd MMM yyyy HH:mm" DisplayFormatString = "dd MMM yyyy HH:mm"/> </Grid> </UserControl>

public partial class DateTimeEdit : UserControl
    {    
        public static readonly DependencyProperty DisplayFormatStringProperty =
          DependencyProperty.Register("DisplayFormatString", typeof(string), typeof(DateTimeEdit), new PropertyMetadata(0));

        public static readonly DependencyProperty MaskProperty =
          DependencyProperty.Register("Mask", typeof(string), typeof(DateTimeEdit), new PropertyMetadata(0));


        public string DisplayFormatString
        {
            get { return (string)GetValue(DisplayFormatStringProperty); }
            set { SetValue(DisplayFormatStringProperty, value); }
        }

        public string Mask
        {
            get { return (string)GetValue(MaskProperty); }
            set { SetValue(MaskProperty, value); }
        }

        public static void OnDisplayFormatStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as DateTimeEdit).localDateEdit.DisplayFormatString = (string)e.NewValue;
        }

        public static void OnMaskChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as DateTimeEdit).localDateEdit.Mask = (string)e.NewValue;
        }
}

我已将依赖属性添加到父控件

Default value type does not match type of property 'DisplayFormatString'

但是,当我尝试在父控件上设置属性时,我得到一个与错误输入格式有关的异常。 <userControls:DateTimeEdit Mask="dd MMM yyyy" DisplayFormatString="dd MMM yyyy"/>

UserControl用法。

let headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");

我是否正确公开了嵌套的Dependency属性?

1 个答案:

答案 0 :(得分:0)

PropertyMetadata(object defaultValue) constructor使用其object参数作为依赖项属性的默认值。这里...

new PropertyMetadata(0)

...您传递一个整数作为String属性的默认值。这就是异常的含义。

尝试null这两个属性:

public static readonly DependencyProperty DisplayFormatStringProperty =
  DependencyProperty.Register("DisplayFormatString", typeof(string), 
        typeof(DateTimeEdit), new PropertyMetadata(null));

public static readonly DependencyProperty MaskProperty =
  DependencyProperty.Register("Mask", typeof(string), 
        typeof(DateTimeEdit), new PropertyMetadata(null));

"",如果合适的话。