Reputation: 1568
How to convert this property to a dependency property ? Regarding that everybody just said that "Do not use logic in dependency property" and didn't proposed a remedy for that :
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
}
}
I want to convert it to this :
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);
}
}
I want to convert the value which is going to be written in this dependency property and also update UIElements.
And also I want to convert a value from an UIElement and return the converted value whenever it's going to be read.
So you see that I can't have a simple backing variable.
Please somebody give me a pattern to implement this.
Thanks for your attention.
Upvotes: 0
Views: 1013
Reputation: 17083
Yes, you can.
You have to bind your UIElement property
to this DependencyProperty
and use a Converter
. See How to: Convert Bound Data.
BTW: Here you can find the reason, why DependencyProperties shouldn't have additional logic in the property wrapper.
Edit:
<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}}" />
create the converter:
[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
}
}
and add it as a resource:
<src:DateConverter x:Key="dateConverter"/>
Upvotes: 2