2010-04-05 2 views
0

다음과 같이 계층 구조 클래스 구조를 사용하여 트리 뷰를 바인딩합니다.트리 뷰 항목의 이미지를 변경하는 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이 있으며이 원본 = "{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 이미지를 변경하고 모든 사람 treeview 항목이 변경됩니다.

감사

답변

1

은 DataTemplate을 personKey (이것은 누구의 ItemsSource Users (사용자) 모음입니다 customerKey HierarchicalDataTemplate의 ItemTemplate을가 있기 때문에) Person 객체에 바인딩 얻을 것입니다. WPF에서 항상 그렇듯이 로컬 DataContext는 상속 된 DataContext를 재정의하고 DataTemplate 내의 DataContext는 항상 DataTemplate이 구체화되는 객체입니다.

따라서 바인딩 경로 Store.ImagePath은 DataTemplate에 표시되는 Person과 관련하여 해결됩니다. 그러나 Person에는 Store 속성이 없으므로 바인딩이 실패합니다.

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

창 수준의 속성을 참조하는 빠른 아니라 미봉책 방법은 바인딩 RelativeSource를 사용하는 것입니다