2014-10-02 147 views
0

我已經構建了一個WPF用戶控件,其中包含DatePicker和其他控件。我的應用程序是用MVVM設計模式編寫的。我希望能夠將我的用戶控件插入到視圖中,並將用戶控件的DatePicker的SelectedDate屬性綁定到我視圖的ViewModel上的DateTime屬性。我希望顯示的默認值是存儲在我的視圖的viewmodel中的值,並且我希望通過與DatePicker交互來更改日期以更新我的視圖的viewmodel DateTime屬性。在WPF中使用DateTime實現雙向綁定DependencyProperty

我成功地看到DatePicker控件中顯示的正確的邊界值,但是當我更改日期時,我的視圖的viewmodel的DateTime屬性設置器未觸發。

這是我爲我的用戶控件的代碼隱藏:

public partial class AgeDiscountUserControl : UserControl 
{ 
    public AgeDiscountUserControl() 
    { 
     InitializeComponent(); 
    } 

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

    public static readonly DependencyProperty DateTimeProperty = 
     DependencyProperty.Register("DateTime", typeof(DateTime), typeof(AgeDiscountUserControl)); 
} 

而且在我的用戶控件的XAML,我有:

... 
xmlns:my="clr-namespace:jkshay.UserControls" 
... 
<DatePicker Grid.Row="0" SelectedDate="{Binding DateTime, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType=my:AgeDiscountUserControl}}" DockPanel.Dock="Right"/> 
... 

在我看來的視圖模型(其中實現INotifyPropertyChanged) ,我有一個DateTime屬性,我想綁定我的用戶控件的DatePicker的SelectedDate屬性。

... 
private DateTime birthdate; 
public DateTime Birthdate 
{ 
    get { return birthdate; }  
    set 
    { 
     if(birthdate != value) 
     { 
      birthdate = value; 
      NotifyPropertyChanged(() => Birthdate); 
     } 
    } 
} 
... 

最後,在我看來的XAML,我AgeDiscountUserControl的結合是:

... 
<uc:AgeDiscountUserControl DateTime="{Binding Birthdate}"/> 
... 

如前所述,正確的值最初顯示在用戶控件的DatePicker的,而是由DatePicker的別進行更改不會影響綁定屬性。

我在這裏錯過了什麼,或者我只是完全誤解了DependencyProperties?

我應該提到,如果我在我的視圖中插入DatePicker並將其綁定到我的viewmodel的Birthdate屬性,它將按預期工作。

+0

你試過了嗎?Mode = TwoWay? – Sinatr 2014-10-02 13:47:40

+0

我*認爲*默認是雙向的,但我會給那個鏡頭。 – 2014-10-02 13:49:02

+0

就是這樣,Sinatr!謝謝!很快回復帖子。 – 2014-10-02 13:51:51

回答

0

在Sinatr的建議中,我在視圖的XAML中添加了Mode = TwoWay設置,現在一切都按預期工作。

更新相關的XAML是:

<uc:AgeDiscountUserControl DateTime="{Binding Birthdate, Mode=TwoWay}"/> 

我現在看到我的生日製定者射擊時與用戶的交互控制。謝謝你的建議,Sinatr。

1

正如您已經發現的那樣,Binding必須是雙向的,以確保在目標控件的值更改時更新源代碼。但是您不必明確地做到這一點:您可能希望爲DateTime屬性設置雙向綁定的默認值。你可以通過在註冊你的依賴屬性時指定一個標誌來做到這一點:

public static readonly DependencyProperty DateTimeProperty = 
    DependencyProperty.Register(
     "DateTime", 
     typeof(DateTime), 
     typeof(AgeDiscountUserControl), 
     new FrameworkPropertyMetadata(
      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault // <-- 
     ) 
    ); 
相關問題