2010-06-18 124 views
0

我有一個問題,在XAML/WPF結合。 我創建了擴展FrameworkElement的Action類。每個Action都有ActionItem列表。問題是沒有設置ActionItem的Data/DataContext屬性,所以它們始終爲空。WPF綁定問題

XAML:

<my:Action DataContext="{Binding}"> 
    <my:Action.Items> 
     <my:ActionItem DataContext="{Binding}" Data="{Binding}" /> 
    </my:Action.Items> 
</my:Action> 

C#:

public class Action : FrameworkElement 
{ 
    public static readonly DependencyProperty ItemsProperty = 
     DependencyProperty.Register("Items", typeof(IList), typeof(Action), 
            new PropertyMetadata(null, null), null); 

    public Action() 
    { 
     this.Items = new ArrayList(); 
     this.DataContextChanged += (s, e) => MessageBox.Show("Action.DataContext"); 
    } 

    public IList Items 
    { 
     get { return (IList)this.GetValue(ItemsProperty); } 
     set { this.SetValue(ItemsProperty, value); } 
    } 
} 

public class ActionItem : FrameworkElement 
{ 
    public static readonly DependencyProperty DataProperty = 
     DependencyProperty.Register("Data", typeof(object), typeof(ActionItem), 
      new PropertyMetadata(
       null, null, (d, v) => 
       { 
        if (v != null) 
         MessageBox.Show("ActionItem.Data is not null"); 
        return v; 
       } 
      ), null 
     ); 

    public object Data 
    { 
     get { return this.GetValue(DataProperty); } 
     set { this.SetValue(DataProperty, value); } 
    } 

    public ActionItem() 
    { 
     this.DataContextChanged += (s, e) => MessageBox.Show("ActionItem.DataContext"); 
    } 
} 

任何想法?

+0

什麼是容器的DataContext?即第一{}綁定在XAML中 – kiwipom 2010-06-18 10:35:13

回答

3

項目不動作控制的孩子,所以DataContext的是不傳播它。你可能會做一些事情來解決它。

最簡單的方法是重寫Action.OnPropertyChanged方法,如果物業== e.DataContextProperty然後分配給e.NewValue每個動作項目。這是最簡單但不是很好的解決方案,因爲如果將新操作添加到Items列表中,它將不會獲取當前數據上下文。

第二種方式是自ItemsControl繼承行動,併爲其提供定製控件模板。

+0

我已經改變了行動基類的ItemsControl和它的作品。謝謝。 – Krzysztof 2010-06-18 19:50:03

+0

@Lolo接受這個答案,如果它結束是正確的,點擊左邊的複選標記。 – Donnie 2010-07-10 22:09:32