2010-06-18 125 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