2010-04-06 3 views
0

Bellow - это код и Xaml для демонстрационного приложения для просмотра данных и wpf. Проблема связана с тем, что свойство Store.ImagePath для узла пользователя не работает. То есть изображение не отображается.Связывание данных: доступ к дочернему элементу свойства AncestorType

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

Вот код-за

namespace TreeViewDemo 
{ 
/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
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 store = new Store(); 
     store.AllCustomers.Add(customers); 
     this.DataContext = store; 
    } 
} 

public class Store : INotifyPropertyChanged 
{ 
    string imagePath = "imageone.png"; 

    public Store() 
    { 
     AllCustomers = new ObservableCollection<Customers>(); 
    } 

    public string StoreName 
    { 
     get 
     { 
      return "ABC Store"; 
     } 
    } 
    public ObservableCollection<Customers> AllCustomers 
    { 
     get; 
     set; 
    } 
    public string ImagePath 
    { 
     get 
     { 
      return imagePath; 
     } 
     set 
     { 
      if (value == imagePath) return; 
      imagePath = value; 

      this.OnPropertyChanged("ImagePath"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
public class Customers 
{ 
    public string Label 
    { 
     get 
     { 
      return string.Format("People({0})", Users.Count()); 
     } 
    } 
    public List<Person> Users 
    { 
     get; 
     set; 
    } 
} 
public class Person : INotifyPropertyChanged 
{ 
    public string Name 
    { 
     get; 
     set; 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
} 

и вот Xaml.

<Window x:Class="TreeViewDemo.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:TreeViewDemo" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources > 
    <DataTemplate DataType="{x:Type local:Person}" x:Key="personKey" > 
     <StackPanel Orientation="Horizontal" > 
      <Image Source="{Binding Path=Store.ImagePath, RelativeSource={RelativeSource AncestorType={x:Type local:Store}}}" /> 
      <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 .}" Height="260" Width="363" Canvas.Left="81" Canvas.Top="45"> 
      <TreeViewItem ItemsSource="{Binding AllCustomers}" ItemTemplate="{StaticResource customerKey}" Header="{Binding StoreName}"></TreeViewItem> 
     </TreeView> 
    </Canvas> 
</Grid> 
</Window> 

Все файлы находятся в том же каталоге.

Благодаря

+0

Вот где проблема. Связывание кажется неспособным видеть привязку к древнему типу. – Jama64

ответ

3

Относительный источник используется для просмотра объекта в визуальном дереве. Вы просите его найти ближайший Store в визуальном дереве. Так как Store не может быть даже в визуальном дереве, поиск завершится неудачно и даст null. То, что вы на самом деле хотите это DataContext корня Window, так как именно там ваш Store проводится:

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

Спасибо, Кент, что работает. – Jama64

+0

Почему DataContext.Store.ImagePath не работает? – Jama64

+0

Поскольку 'DataContext' каждого' TreeViewItem' установлен неявным образом WPF для элемента данных, для которого был создан «TreeViewItem». –

Смежные вопросы