C# WPF绑定问题
我在XAML/WPF中绑定时遇到问题。 我创建了扩展FrameworkElement的Action类。每个操作都有ActionItem的列表。问题是ActionItem的Data/DataContext属性没有设置,所以它们总是空的 XAML:C# WPF绑定问题,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我在XAML/WPF中绑定时遇到问题。 我创建了扩展FrameworkElement的Action类。每个操作都有ActionItem的列表。问题是ActionItem的Data/DataContext属性没有设置,所以它们总是空的 XAML: 有什么想法吗?项不是动作控件的子项,因此DataContext不会传播到其子项。你可以做一些事情来修复它 最简单的方法是重写Action.OnPropertyChanged方法,如果Property==e.DataContextProperty,则将e.
有什么想法吗?项不是动作控件的子项,因此DataContext不会传播到其子项。你可以做一些事情来修复它 最简单的方法是重写Action.OnPropertyChanged方法,如果Property==e.DataContextProperty,则将e.NewValue分配给每个操作项。这是一个最简单但不是很好的解决方案,因为如果将新操作添加到项目列表中,它将无法获取当前数据上下文
第二种方法是从ItemsControl继承操作,并为其提供自定义控件模板。项不是操作控件的子项,因此DataContext不会传播到其子项。你可以做一些事情来修复它 最简单的方法是重写Action.OnPropertyChanged方法,如果Property==e.DataContextProperty,则将e.NewValue分配给每个操作项。这是一个最简单但不是很好的解决方案,因为如果将新操作添加到项目列表中,它将无法获取当前数据上下文
第二种方法是从ItemsControl继承操作,并为其提供自定义控件模板。容器的DataContext是什么?ie在XAML中的第一个{Binding}容器的DataContext是什么?ie您的xamlI中的第一个{Binding}已经将Action基类更改为ItemsControl,并且可以正常工作。THX.@Lolo接受这个答案,如果它最终是正确的,请单击它左边的复选标记。我已将操作基类更改为ItemsControl,它可以工作。THX.@Lolo接受这个答案,如果答案是正确的,请单击它左边的复选标记。
<my:Action DataContext="{Binding}">
<my:Action.Items>
<my:ActionItem DataContext="{Binding}" Data="{Binding}" />
</my:Action.Items>
</my:Action>
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");
}
}