如何向依赖属性添加逻辑?

时间:2012-04-18 08:18:36

标签: wpf logic dependency-properties

如何将此属性转换为依赖项属性?关于这一点,每个人都只是说“不要在依赖属性中使用逻辑”,并没有提出补救措施:

    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 个答案:

答案 0 :(得分:1)

是的,你可以。

您必须将UIElement property绑定到此DependencyProperty并使用Converter。请参阅How to: Convert Bound Data

BTW: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"/>