2012-11-06 71 views
0

我想創建一個自定義的DependencyProperty的用戶控件自定義的DependencyProperty自定義數據類型

public Table Grids 
    { 
     get { return (Table)GetValue(GridsProperty); } 
     set { SetValue(GridsProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Grids. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty GridsProperty = 
       DependencyProperty.Register("Grids", typeof(Table), 
       typeof(MyViewer), new UIPropertyMetadata(10)); 

這裏表是用來存儲行&欄自定義數據類型。這會幫助我像使用它們;

<my:MyViewer 
    HorizontalAlignment="Left" 
    Margin="66,54,0,0" 
    x:Name="MyViewer1" 
    VerticalAlignment="Top" 
    Height="400" 
    Width="400" 
    Grids="10"/> 

<my:MyViewer 
    HorizontalAlignment="Left" 
    Margin="66,54,0,0" 
    x:Name="MyViewer1" 
    VerticalAlignment="Top" 
    Height="400" 
    Width="400" 
    Grids="10,20"/> 

我試圖作爲定義表的數據類型;

public class Table 
    { 
     public int Rows { get; set; } 
     public int Columns { get; set; } 

     public Table(int uniform) 
     { 
      Rows = uniform; 
      Columns = uniform; 
     } 

     public Table(int rows, int columns) 
     { 
      Rows = rows; 
      Columns = columns; 
     } 
    } 

但它不工作;當我在XAML中使用網格=「10」時,它會中斷。 任何人都可以幫助我實現這一目標嗎?

回答

2

默認值:

new FrameworkPropertyMetadata(new Table()) 

new FrameworkPropertyMetadata(null) 

然後在XAML中,你可以做以下元數據的類型是錯誤的。這會在加載MyViewer類時導致異常。將默認值設置爲new Table(10)

除此之外,XAML/WPF不會通過調用正確的構造函數將字符串"10""10,20"自動轉換爲Table類的實例。您必須編寫TypeConverter才能執行此轉換。

一個簡單的類型轉換器看起來是這樣的:

public class TableConverter : TypeConverter 
{ 
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
    { 
     return sourceType == typeof(string); 
    } 

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) 
    { 
     string tableString = value as string; 
     if (tableString == null) 
     { 
      throw new ArgumentNullException(); 
     } 

     string[] numbers = tableString.Split(new char[] { ',' }, 2); 
     int rows = int.Parse(numbers[0]); 
     int columns = rows; 

     if (numbers.Length > 1) 
     { 
      columns = int.Parse(numbers[1]); 
     } 

     return new Table { Rows = rows, Columns = columns }; 
    } 
} 

的類型轉換器將與你的表類像這樣的關聯:

在XAML
[TypeConverter(typeof(TableConverter))] 
public class Table 
{ 
    ... 
} 
3

是不是您在註冊方法中設置的默認值數據類型不匹配?我相信你想第一FrameworkPropertyMetadata參數是這樣的:在屬性

<my:MyViewer> 
    <my:MyViewer.Grids> 
     <Table Rows="10" Column="20"/> 
    </my:MyViewer.Grids> 
</my:MyViewer> 
+0

然後你承擔責任:水災做到以下幾點:

XamlZealot

+0

謝謝!我可以用這種方式達到結果。然而,@Clemens解決方案更具有吸引力和簡單性。 <我:MyViewer 的Horizo​​ntalAlignment = 「左」 保證金= 「66,54,0,0」 X:NAME = 「MyViewer1」 VerticalAlignment = 「評出的」 HEIGHT = 「400」 WIDTH = 「400」 網格= 「10,20」/> – Riju