Привязка данных: дочерний доступ к свойству AncestorType - PullRequest
0 голосов
/ 06 апреля 2010

Ниже приведен код и Xaml для демонстрационного приложения для просмотра данных и wpf. Проблема заключается в привязке свойства Store.ImagePath к узлу person, который не работает. То есть изображение не отображается.

<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>

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

Спасибо

1 Ответ

3 голосов
/ 06 апреля 2010

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

<Image Source="{Binding DataContext.ImagePath, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...