代码之家  ›  专栏  ›  技术社区  ›  Krzysztof

WPF绑定问题

  •  0
  • Krzysztof  · 技术社区  · 15 年前

    我在XAML/WPF中绑定有问题。 我创建了扩展FrameworkElement的Action类。每个操作都有ActionItem列表。问题是ActionItem的Data/DataContext属性没有设置,所以它们总是空的。

    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");
        }
    }
    

    1 回复  |  直到 15 年前
        1
  •  3
  •   STO    15 年前

    最简单的方法是重写Action.OnPropertyChanged方法,如果Property==e.DataContextProperty,则为每个操作项分配e.NewValue。这是最简单但不是很好的解决方案,因为如果将新操作添加到项目列表中,它将无法获取当前数据上下文。

    第二种方法是从ItemsControl继承操作,并为其提供自定义控件模板。

    推荐文章