代码之家  ›  专栏  ›  技术社区  ›  Joseph Sturtevant

WPF中的变量绑定

  •  5
  • Joseph Sturtevant  · 技术社区  · 17 年前

    我正在为一个富树视图创建一个用户控件(一个具有用于重命名节点、添加子节点等的上下文菜单的视图)。我希望能够使用此控件来管理或导航我将创建的任何分层数据结构。我目前让它为实现以下接口的任何数据结构工作(实际上不需要实现接口,但是只需要这些成员的存在):

    interface ITreeItem
    {
        string Header { get; set; }
        IEnumerable Children { get; }
    }
    

    然后在我的用户控件中,我使用模板将树绑定到数据结构,如下所示:

    <TextBlock x:Name="HeaderTextBlock" Text="{Binding Path=Header}" />
    

    我想做的是在我的richtreeview中定义每个成员的名称,允许它适应一系列不同的数据结构,如:

    class MyItem
    {
        string Name { get; set; }
        ObservableCollection<MyItem> Items;
    }
    
    <uc:RichTreeView ItemSource={Binding Source={StaticResource MyItemsProvider}} 
        HeaderProperty="Name" ChildrenProperty="Items" />
    

    是否有任何方法可以将用户控件内绑定的路径公开为该用户控件的公共属性?解决这个问题还有别的办法吗?

    1 回复  |  直到 17 年前
        1
  •  2
  •   burning_LEGION    13 年前

    也许这会有所帮助:

    在头依赖属性上设置HeaderProperty属性时创建新绑定:

    Header属性是您的日常依赖属性:

        public string Header
        {
            get { return (string)GetValue(HeaderProperty); }
            set { SetValue(HeaderProperty, value); }
        }
    
        public static readonly DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(string), typeof(ownerclass));
    

    您的校长财产的性质如下:

        public static readonly DependencyProperty HeaderPropertyProperty =
            DependencyProperty.Register("HeaderProperty", typeof(string), typeof(ownerclass), new PropertyMetadata(OnHeaderPropertyChanged));
    
        public string HeaderProperty        
        {
            get { return (string)GetValue(HeaderPropertyProperty); }
            set { SetValue(HeaderPropertyProperty, value); }
        }
    
       public static void OnHeaderPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue != null)
            {
                ownerclass c = (ownerclass) obj;
    
                Binding b = new Binding();
                b.Path = new PropertyPath(args.NewValue.ToString());
                c.SetBinding(ownerclass.HeaderProperty, b);
            }
        }
    

    HeaderProperty是正常的日常DependencyProperty,其方法在HeaderProperty更改时立即调用。因此,当它更改时,它会在头上创建一个绑定,该绑定将绑定到您在HeaderProperty中设置的路径。:)

    推荐文章