2010-04-05 88 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}}}" />