2009-09-03 70 views
0

我正在寫一個簡單的日曆控件,以便更好地理解WPF。我有一個包含兩個按鈕(下,prevoious)一個CalendarHeader控制並定義爲當孩子更改屬性值時通知父級

public static DependencyProperty CurrentMonthProperty = DependencyProperty.Register 
     ("CurrentMonth", typeof(int), typeof(CalendarHeader), new FrameworkPropertyMetadata(DateTime.Now.Month, FrameworkPropertyMetadataOptions.None, CurrentMonthChangedCallBack)); 

需要如此交互以與CalenderHeader是CalendarMonth另一個控制一個依賴屬性CurrentMonth。要在一個月CalendarHeader改變通知CalendarMonth,我加入業主依賴屬性把它作爲

public static DependencyProperty CurrentMonthProperty = CalendarHeader.CurrentMonthProperty.AddOwner 
     (typeof(CalendarMonth), new FrameworkPropertyMetadata(DateTime.Now.Month, CurrentMonthChangedCallBack)); 

當CalendarHeader改變CurrentMonth的價值,我認爲這也將引發CalendarMonth的CurrentMonthChangedCallBack但它不是這樣做。如何通知CalendarMonth CalendarHeader中CurrentMonth的值已更改。 感謝百萬

回答

1

一種選擇是創建一個基本控件(我們稱之爲CalendarPrimitive)來存儲CurrentMonthProperty。當您使用FrameworkPropertyMetadataOptions.Inherit註冊屬性註冊時。

如果您從CalendarPrimitive派生CalendarHeaderControl和CalendarMonth控件,該值將自動從CalendarHeader傳遞給CalendarMonth(假設CalendarMonth嵌套在CalendarHeader中)。

如果您的頂級Calendar控件也是從CalendarPrimitive派生的,它將負責存儲CurrentMonthProperty,並且它的所有子項都將繼承該值。

此外,您可能需要定義CalendarPrimitive可用於通知它已更改CurrentMonth的頂級的CurrentMonthChanged RoutedEvent。

您的頂級日曆將偵聽此事件並相應地更改其CurrentMonth(向樹中傳播更改)。

+0

Mike, 我不確定這是否會奏效。首先,CalendarHeader嵌套在CalendarMonth內。其次,它是CalendarHeader,它具有更改月份的按鈕。因此從基類繼承不會做太多的事情,因爲它不是改變值的基類,而是CalendarHeader。 – Sheraz 2009-09-03 20:46:41

+0

依賴屬性繼承導致在父項上設置的值應用於其所有子項(這就是爲什麼在窗口上設置背景會使所有子項都變爲背景的原因)。 通過使用路由事件,會通知家長有人想要更改當前月份。當家長這樣做時,所有的孩子都會得到更新。 – 2009-09-04 12:45:50

+0

這是我所做的解決了這個問題。我按照你的定義添加了一個基類。由於CalendarHeader嵌套在CalendarMonth中,因此我不會使用具有繼承性的DependencyProperty。相反,我在基類中定義了一個路由事件。在標題中提出該事件。在CalendarMonth中註冊一個處理程序。將發件人轉換爲CalendarHeader以獲取Current Month的值並設置e.Handled = true。這讓它工作。 謝謝 – Sheraz 2009-09-06 19:33:47