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

时间:2009-09-02 04:36:04

标签: wpf data-binding

我有一个班级,

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 个答案:

答案 0 :(得分:0)

要在Name属性更改时运行代码,请在依赖项属性注册中指定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
}

然后,您的OnNameChanged处理程序可以填充PageInformation的其他属性。

请注意,如果您希望更新其他 WPF元素以响应Name更改,您可以通过将其属性绑定到PageInformation的Name属性来实现。