2012-04-17 106 views
1

我需要包裝Windows窗體DateTimePicker以在我的WPF 3.5應用程序中使用它。我做了一個控制了它:WPF中的Windows窗體控件包裝無法正常工作

<UserControl><WindowsFormsHost> 
<wf:DateTimePicker x:Name="picker" ValueChanged="DateTimePicker_ValueChanged"/> 
</WindowsFormsHost></UserControl> 

這裏是依託代碼:

bool suppressUpdates; 

    public DatePicker() 
    { 
     InitializeComponent(); 
    } 

    private void DateTimePicker_ValueChanged(object sender, EventArgs e) 
    { 
     if(!suppressUpdates) 
      SetValue(SelectedDateProperty, picker.Value); 
    } 

    public DateTime SelectedDate 
    { 
     get {return (DateTime)GetValue(SelectedDateProperty); } 
     set 
     { 
      suppressUpdates = true; 
      picker.Value = value; 
      SetValue(SelectedDateProperty, value); 
      suppressUpdates = false; 
     } 
    } 

    public static readonly DependencyProperty SelectedDateProperty = 
    DependencyProperty.Register("SelectedDate", typeof(DateTime), 
    typeof(DatePicker), new UIPropertyMetadata(DateTime.Now)); 

然後我用它在WPF窗口:

<mui:DatePicker Width="300" SelectedDate="{Binding 
Path=TheDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 

它必然到INotifyPropertyChanged -enabled viewmodel。所有其他控件綁定到它只是很好,但我的DateTimePicker沒有得到viewmodel中指定的日期值。但是,它將價值變化傳播給它。

我在做什麼錯?

回答

1

好吧,它很簡單。

private void DateTimePicker_ValueChanged(object sender, EventArgs e) 
    { 
     SetValue(SelectedDateProperty, picker.Value); 
    } 

    public DateTime SelectedDate 
    { 
     get { return (DateTime)GetValue(SelectedDateProperty); } 
     set { SetValue(SelectedDateProperty, value); } 
    } 

    public static readonly DependencyProperty SelectedDateProperty = 
     DependencyProperty.Register("SelectedDate", typeof(DateTime), typeof(DatePicker), new UIPropertyMetadata(DateTime.Now, textChangedCallback)); 

    private static void textChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     DatePicker input = (DatePicker)d; 
     input.picker.Value = (DateTime)e.NewValue; 
    }