Question

I created a dependency property on a custom user control and problem is that the "OnPeriodTypeChangedHandler" Property Change Call Back only fire once when control is created for the first time, subsequently if I try to call the property via Binding it doesn't fire at all. Any ideas?

#region PeriodType
    public static readonly DependencyProperty PeriodTypeProperty =
         DependencyProperty.Register(
            "PeriodType",
            typeof(PeriodTypeEnum),
            typeof(Period),
            new FrameworkPropertyMetadata(
                PeriodTypeEnum.None,
                FrameworkPropertyMetadataOptions.AffectsRender,
                new PropertyChangedCallback(OnPeriodTypeChangedHandler)
            )
    );

    public static void OnPeriodTypeChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        // Get instance of current control from sender
        // and property value from e.NewValue

        // Set public property on TaregtCatalogControl, e.g.
        ((Period)sender).PeriodType = (PeriodTypeEnum)e.NewValue;
        if ((PeriodTypeEnum)e.NewValue == PeriodTypeEnum.Month)
            ((Period)sender).Periods = ((Period)sender).GetMonthlyPeriods();
        if ((PeriodTypeEnum)e.NewValue == PeriodTypeEnum.Quarter)
            ((Period)sender).Periods = ((Period)sender).GetQuarterlyPeriods();
    }

    public PeriodTypeEnum PeriodType
    {
        get 
        {
            return (PeriodTypeEnum)GetValue(PeriodTypeProperty); 
        }
        set 
        { 
            SetValue(PeriodTypeProperty, value);                
        }
    }

    #endregion

No correct solution

OTHER TIPS

In case you want your DP to bind TwoWay by default, you can specify it at time of DP registration using FrameworkPropertyMetadataOptions.BindsTwoWayByDefault. This way you don't have to set mode to TwoWay at time of binding.

    public static readonly DependencyProperty PeriodTypeProperty =
     DependencyProperty.Register(
        "PeriodType",
        typeof(string),
        typeof(MyTextBox),
        new FrameworkPropertyMetadata(
            PeriodTypeEnum.None,
            FrameworkPropertyMetadataOptions.AffectsRender
               | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, <- HERE
            new PropertyChangedCallback(OnPeriodTypeChangedHandler)
        )
);

I think I found the solution in this particular instance by changing the Mode property to "TwoWay" in ViewModel for its data binding property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top