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

如何使自定义类在wpf中可绑定?

  •  0
  • Vijay  · 技术社区  · 17 年前

    我有一节课,

    internal class PageInformation : DependencyObject
    {
        public static DependencyProperty NameProperty =
           DependencyProperty.Register("Name", typeof(string), typeof(PageInformation));
    
        public static DependencyProperty PageUriProperty =
           DependencyProperty.Register("PageUri", typeof(string), typeof(PageInformation));
    
        public string Name
        {
            get;
            set;
        }
    
        public Uri PageUri
        {
            get;
        }
    }
    

    如何将其绑定到某些数据源?

    我的想法是有一个XML文件来存储关于应用程序中所有页面的信息,让这个类 <Page.Resources> 并将其绑定到xml文件。

    XML文件如下所示:

    <Elements>
          <Element Name="Administration" DisplayName="Administration" Value="1" PageUri="Administration.xaml" >
                <Element Name="Categories" DisplayName="Categories" Value="2" PageUri="Administration.xaml" ></Element>
                <Element Name="Goals" DisplayName="Goals" Value="3" PageUri="Administration.xaml" ></Element>
                <Element Name="Settings" DisplayName="Settings" Value="4" PageUri="Administration.xaml" ></Element>
          </Element>
    </Elements>
    

    我想要这样的xaml:

        <Page.Resources>
                <local:PageInformation 
                    x:Key="pageInfo" 
                    Name="{Binding XPath=/Elements/Element[@Name='Administration']}" 
                    Source="/samples.xml" >
                </local:PageInformation>
        </Page.Resources>
    

    当我有价值的时候 Name 属性,我还想编写代码来填充其他属性(可能是通过使用数据上下文?).

    有人能告诉我怎样才能做到这一点吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   itowlson    17 年前

    若要在名称属性更改时运行代码,请在依赖项属性注册中指定PropertyChangedCallback:

    public static DependencyProperty NameProperty =
      DependencyProperty.Register("Name", typeof(string), typeof(PageInformation),
      new FrameworkPropertyMetadata(OnNameChanged));
    
    private static void OnNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      // do whatever you want here
    }
    

    然后,您的OnNAME变处理程序可以填充页信息的其他属性。

    注意如果你想要 其他 要响应名称更改而更新的wpf元素,可以将其属性绑定到pageinformation的name属性。

    推荐文章