2009-09-02 19 views
0

我有一個類,如何使自定義類在WPF中可綁定?

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財產,我想編寫代碼來填充其他屬性(可能通過使用數據上下文?)。

有人可以告訴我怎麼做到這一點?

回答

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元素更新以響應名稱更改,您可以通過將它們的屬性綁定到PageInformation的Name屬性來完成此操作。