2009-08-07 47 views
0

Another post描述如何訪問XAML中代碼隱藏變量在XAML中訪問代碼隱藏對象

但是,我想從XAML訪問代碼隱藏對象中的變量。被稱爲FeedData的代碼隱藏對象被聲明爲類型的依賴項屬性FeedEntry。這個類只是一個帶有字符串和日期時間屬性的容器類。

代碼隱藏的屬性definitition是這樣的:

public FeedEntry FeedData 
     { 
      get { return (FeedEntry)GetValue(FeedDataProperty); } 
      set { SetValue(FeedDataProperty, value); } 
     } 
     public static readonly DependencyProperty FeedDataProperty = 
      DependencyProperty.Register("FeedData", typeof(FeedReaderDll.FeedEntry), typeof(FeedItemUserControl), 
      new FrameworkPropertyMetadata(new FeedEntry(){ Title="Hi!", Published=DateTime.Now })); 

在XAML我這樣做,這是不行的:

<UserControl x:Class="FeedPhysics.UserControls.FeedItemUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="40" Width="200" 
    Background="Blue" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}" 
    x:Name="xRoot"> 
    <StackPanel> 
     <TextBlock Text="{Binding Title}" Foreground="White"/> 
     <TextBlock Text="{Binding Published}" Foreground="White"/> 
    </StackPanel> 
</UserControl> 

但是,如果我在代碼隱藏的構造器重寫窗口的DataContext的設置,將工作!像這樣:

xRoot.DataContext = FeedData; 

我明白爲什麼它在datacontext設置在codebehing中時工作。但我想找出一種方法來獲取在代碼隱藏中聲明的對象中的變量。因爲,XAML應該可以做到,對吧?

感謝您提前解答。

回答

0

嘗試的StackPanel的DataContext的設置到feeddata對象:

<StackPanel DataContext="{Binding FeedData}"> 

...

這將迫使StackPanel的看的DependencyProperty,並在它的所有元素會的性質被引用了feeddata。

只要您將DataContext定義爲「FeedData」,在您綁定到它的屬性的可視元素上方的邏輯樹中的某處,它就可以工作。

+0

就是這樣!感謝幫助! – Pompair 2009-08-07 13:20:14