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 转换一个值,并在要读取它时返回转换后的值。

所以你看我不能有一个简单的支持变量。

请有人给我一个模式来实现这个。

感谢您的关注。

4

1 回答 1

2

是的你可以。

您必须将您的绑定UIElement property到此DependencyProperty并使用Converter. 请参阅如何:转换绑定数据

顺便说一句:在这里你可以找到原因,为什么 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"/>
于 2012-04-18T09:05:44.207 回答