views:

123

answers:

1

Hello,

My goal is to have a user select a year and a month. Translate the selection into a date and have the user control send the date back to my view model. That part works for me....However, I cannot get the ViewModel's initial date to set those drop downs.

   public static readonly DependencyProperty Date =
      DependencyProperty.Register("ReturnDate", typeof(DateTime), typeof(DatePicker),
      new FrameworkPropertyMetadata{BindsTwoWayByDefault = true,});

   public DateTime ReturnDate
     {
        get { return Convert.ToDateTime(GetValue(Date)); }
        set
        {
            SetDropDowns(value);
            SetValue(Date, value);
        }
     }

The SetDropDowns(value) just sets the selected items on the combo boxes, however, the program never makes it to that method.

On the view I am using:

  <cc1:DatePicker ReturnDate="{Binding Path=StartDate, Mode=TwoWay}" IsStart="True" />

If this has been answered, then my bad. I looked around and didn't see anything that worked for me. Thus, when the program loads how do I get the value from the view model to a method in order to set the combo boxes?

Thanks,

-Scott

+1  A: 

When you use a Dependency Property, the CLR property Setter is never fired (when binding sets the property).

The proper way to do this is to use a PropertyChangedCallback on your dependency property:

public static readonly DependencyProperty Date =
  DependencyProperty.Register("ReturnDate", typeof(DateTime), typeof(DatePicker),
  new FrameworkPropertyMetadata(
        DateTime.Now, 
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        new PropertyChangedCallback(dateChanged)));

public DateTime ReturnDate
 {
    get { return Convert.ToDateTime(GetValue(Date)); }
    set
    {
        SetDropDowns(value);
        SetValue(Date, value);
    }
 }

private static void dateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  DatePicker instance = d as DatePicker;
  instance.SetDropDowns((DateTime)e.NewValue);
}
Reed Copsey
Thanks for the quick reply, d.SetDropDowns should be intance.SetDropDowns and the name of the call back should be dateChanged. (I only point that out for future readers). Thanks again.
BlargINC
@BlargINC: I corrected it - sorry - that's what happens sometimes when I try to type really fast in here ;) Did this correct your issue? If so, you should mark it as the answer (little check mark - I only mention since you're a new user ;) )
Reed Copsey
Yep it worked. Thanks
BlargINC