2012-04-18 64 views
0

如何將此屬性轉換爲依賴項屬性?至於大家剛纔說的「不要依賴項屬性使用邏輯」,並沒有提出一個補救措施:如何向依賴項屬性添加邏輯?

public DateTime? SelectedDateGeorgian 
    { 
     get 
     { 
      //choose a control based on this "user control" current mode 
      //and return its value 
     } 


     set 
     { 
      //choose a control based on this "user control" current mode 
      // and set its property after some manipulations on the value 
     } 
    } 

我想將它轉化成這樣:

public static readonly DependencyProperty SelectedDateGeorgianProperty = 
    DependencyProperty.Register("SelectedDateGeorgian", typeof(DateTime?), typeof(MyDatePicker), new PropertyMetadata(default(DateTime?))); 

    public DateTime? SelectedDateGeorgian 
    { 
     get 
     { 
      //Its prohobited to do something here ! So what should I do ? 
      //How should I select a control and return its value here ? 
      //I can't have a simple backing variable because I should do some conversion here     

      return (DateTime?)GetValue(SelectedDateGeorgianProperty); 
     } 
     set 
     { 
      //I want to convert received value here and 
      // and after that update some UI properties in this user control 

      SetValue(SelectedDateMiladiProperty, value); 
     } 
    } 

我想轉換要寫入此依賴項屬性中的值並更新UIElements。

而且我還想從UIElement轉換一個值,並在每次讀取它時返回轉換後的值。

所以你看到我不能有一個簡單的支持變量。

請有人給我一個模式來實現這一點。

感謝您的關注。

回答

1

是的,你可以。

您必須將您的UIElement property與此DependencyProperty綁定並使用Converter。請參閱How to: Convert Bound Data

順便說一句:Here你可以找到原因,爲什麼DependencyProperties不應該在屬性包裝中有額外的邏輯。

編輯:

<DatePicker Name="dp1" 
      SelectedDate="{Binding Path=SelectedDateGeorgian, 
            RelativeSource="{RelativeSource AncestorType=UserControl}"}" /> 
<DatePicker Name="dp2" 
      SelectedDate="{Binding Path=SelectedDateGeorgian, 
            RelativeSource="{RelativeSource AncestorType=UserControl}", 
            Converter={StaticResource dateConverter}}" /> 

創建轉換器:

[ValueConversion(typeof(DateTime?), typeof(DateTime?))] 
public class DateConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // your conversions 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // your backconversions 
    } 
} 

並將其添加爲一個資源:

<src:DateConverter x:Key="dateConverter"/> 
+0

感謝您的關注。但是當我們談論用戶控制之外時,這是正確的。但我的問題是在用戶控制之內。 :( – 2012-04-18 09:12:08

+0

你是什麼意思?你能描述'內部'的問題,也許有一些代碼嗎? – LPL 2012-04-18 09:14:48

+0

我的意思是我想要一個用戶控件來爲這個用戶控件的用戶轉換它的值。用戶控件不關心轉換邏輯,我認爲它在上面提供的代碼中很明顯 – 2012-04-18 09:42:51