2010-04-05 106 views
0

我使用Hierarchical類結構綁定樹視圖,如下所示。Wpf觸發器來更改樹視圖項目的圖像

商店 - > ImagePath的 - >列表 - >列表

當我創建DataTemplate中的人,我想用在宣佈person.name 的組合和圖像路徑商店。 這是我的MainWindow.xaml文件背後的代碼。 `public partial class MainWindow:Window { public MainWindow() { InitializeComponent();

 Customers customers = new Customers(); 
     customers.Users = new List<Person> 
     { 
      new Person { Name = "John"}, 
      new Person { Name = "Adam"}, 
      new Person { Name = "Smith"} 
     }; 

     Store root = new Store(); 
     root.ImagePath = "imageone.png"; 
     root.Add(customers); 
     this.DataContext = root; 
    } 
} 


public class Store : ObservableCollection<Customers> 
{ 
    public string ImagePath 
    { 
     get; 
     set; 
    } 
} 
public class Customers 
{ 
    public string Label 
    { 
     get 
     { 
      return string.Format("People({0})", Users.Count()); 
     } 
    } 
    public List<Person> Users 
    { 
     get; 
     set; 
    } 
} 
public class Person 
{ 
    public string Name 
    { 
     get; 
     set; 
    } 
}` 

這裏是xaml和this Source =「{Binding Store.ImagePath}」不起作用。

<Window.Resources > 
    <DataTemplate DataType="{x:Type local:Person}" x:Key="personKey" > 
     <StackPanel Orientation="Horizontal" > 
      <Image Source="{Binding Store.ImagePath}"></Image> 
      <TextBlock Text="{Binding Name}" /> 
     </StackPanel> 
    </DataTemplate> 
    <HierarchicalDataTemplate x:Key="customerKey" ItemsSource="{Binding Users}" ItemTemplate="{StaticResource personKey }" > 
     <TextBlock Text="{Binding Label}" FontWeight="Bold"/> 
    </HierarchicalDataTemplate> 
</Window.Resources> 
<Grid> 
    <Canvas> 
     <Button HorizontalAlignment="Left" DockPanel.Dock="Top" Height="29" Width="112" Canvas.Left="123" Canvas.Top="5">Image one</Button> <Button HorizontalAlignment="Left" VerticalAlignment="Top" DockPanel.Dock="Top" Height="28" Width="119" Canvas.Left="249" Canvas.Top="7">Image two</Button> 
     <TreeView HorizontalAlignment="Stretch" Name="treeView1" VerticalAlignment="Stretch" 
       ItemsSource="{Binding .}" ItemTemplate="{StaticResource customerKey}" Height="260" Width="363" Canvas.Left="81" Canvas.Top="45" /> 
    </Canvas> 
</Grid> 

我也想改變programaticaaly圖像和所有的人樹視圖項改變,當我點擊按鈕。

感謝

回答

1

的DataTemplate中personKey是會得到綁定到一個Person對象(因爲它的ItemTemplate中的customerKey HierarchicalDataTemplate,它的ItemsSource爲用戶集合)。和WPF一樣,本地DataContext覆蓋繼承的DataContext,並且DataTemplate中的DataContext始終是DataTemplate實現的對象。

因此綁定路徑Store.ImagePath正在解析相對於DataTemplate中顯示的Person。但是Person沒有Store屬性,所以綁定失敗。

快速而缺憾的方式來引用窗口級屬性是使用的RelativeSource綁定:

<Image Source="{Binding Path=DataContext.Store.ImagePath, 
         RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />