2012-12-06 3 views
4

WPF에서 동일한 기능을 얻으려면 어떤 방법이 있습니까? DataTemplateSelector에서 제공하지만 UserControls에서는 사용할 수 있습니까?xaml에서 데이터 바인딩을 통해 객체 유형에 따라 다른 UserControls를 동적으로로드하십시오.

IEnumerable 개체를 바인딩 할 StackView가 있다고 가정 해 봅시다. 내가 뭘하고 싶은지 어떻게 든, 바인딩 된 IEnumerable의 각 객체 유형에 대해 객체 유형을보고 StackView에 추가 할 UserControl을 결정하는 매핑을 가지고 있습니다. 그래서

, 주어진 세 개의 클래스 :

각 클래스 Building에서 상속 및 UserControl을 정의 그것의 자신의
public class House : Building{} 

public class Apartment : Building{} 

public class Tent : Building{} 

, 나는 그것의 집합을 채울 StackView를 IEnumerable<Building>DataContext를 설정하고 어떻게 든 좀하고 싶습니다 형식에 특정한 UserControl을 가진 자식.

최대한 적은 코드로이 작업을 수행하고 싶습니다. 데이터 바인딩 및 XAML 덕트 테이프가 많을수록 좋습니다.

답변

6

DataTemplate에서 복잡한 사용자 컨트롤을 사용할 수 있습니다. UserControl으로 DataTemplate을 신고하기 만하면됩니다.

예 :

<Window x:Class="WpfApplication4.MainWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:WpfApplication4" 
      Title="MainWindow" Height="300" Width="300" Name="UI" > 
     <Window.Resources> 
      <DataTemplate DataType="{x:Type local:House}" > 
       <local:HouseUserControl DataContext="{Binding}"/> 
      </DataTemplate> 
      <DataTemplate DataType="{x:Type local:Apartment}"> 
       <local:ApartmentUserControl DataContext="{Binding}"/> 
      </DataTemplate> 
     </Window.Resources> 

     <Grid> 
      <ListBox ItemsSource="{Binding ElementName=UI, Path=ListOfBuildings}" /> 
     </Grid> 
    </Window> 
+0

달콤한! 그게 내가 필요한 것. 데이터 소스 유형에 바인딩 할 수 있는지 몰랐습니다. – Turbo

2

잘 모르겠습니다. 어딘가에 리소스의 각 유형에 대한 DataTemplates를 만들고 WPF는 자동으로 각 유형을 렌더링하는 데 사용합니다.

+0

하지만 이미 뒤에 코드의 요금 양을 사용자 정의 (복잡한) 된 UserControls 있습니다. 그래서 DataTemplate은 실제로 작동하지 않습니다. – Turbo

+0

그래서 적절한 UserControl을 포함하는 템플릿을 선언하십시오. – GazTheDestroyer

관련 문제