2016-09-28 79 views
0

我試圖公開嵌套控件的兩個依賴屬性。在這種情況下,MaskDisplayFormatString無法使用嵌套的依賴屬性初始化UserControl

<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'

UserControl用法。

<userControls:DateTimeEdit 
      Mask="dd MMM yyyy" 
      DisplayFormatString="dd MMM yyyy"/> 

我是否正確地暴露嵌套的依賴屬性?

回答

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)); 

或者"",如果合適的話。