2013-10-17 93 views
0

我有多個用戶控件,我想在列表框中顯示它們 讓我們假設我有一個Employee抽象用戶控件,並且我有兩個或多個用戶控件,而不是像AdministrativeEmployee和FactoryEmployee這樣的員工用於每個這些僱員我有不同的數據,但UserControl是非常相似的(相同的大小,幾乎相同的領域),在ViewModel方面我有一個抽象的EmployeeViewModel,AdministrativeEmployeeViewModel和FatoryEmployeeViewModel,在EmployeesView我有ListBox與數據綁定和EmployeesViewModel我有一個ICollection員工WPF將多個用戶控件綁定到列表框

EmployeesView.xaml:

xmlns:local="clr-namespace:Solution.Controls" 

-

<ListBox ItemsSource={Binding Employees}> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <ContentPresenter Content="{Binding}" Name="Presenter" /> 
       <DataTemplate.Triggers> 
        <DataTrigger Value="{x:Type local:AdministrativeEmployeeView}"> 
         <Setter TargetName="Presenter" Property="Content"> 
          <Setter.Value> 
           <local:AdministrativeEmployeeView /> 
          </Setter.Value> 
         </Setter> 
        </DataTrigger> 
        <DataTrigger Value="{x:Type local:FactoryEmployeeView}"> 
         <Setter TargetName="Presenter" Property="Content"> 
          <Setter.Value> 
           <local:FactoryEmployeeView/> 
          </Setter.Value> 
         </Setter> 
        </DataTrigger> 
       </DataTemplate.Triggers> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

EmployeesViewModel.cs:

public ICollection<EmployeeViewModel> Employees { get; set; } 

但是,告訴我System.ItemTemplate在列表框,而不是爲每種類型的員工

的用戶控件
+0

這是一個錯字? 'ItemsSource = {Binding Employees}'應該是'ItemsSource =「{Binding Employees}」'。沒有綁定的DataTrigger是無用的。 – LPL

+2

看起來你在這裏使用的是一個非常迂迴的方法。爲什麼不直接用Type指定DataTemplates?這將自動呈現每個類型及其分配的模板。 – McGarnagle

回答

3

ListBox資源定義兩個數據模板:

<ListBox ItemsSource="{Binding Employees}"> 
    <ListBox.Resources> 
     <DataTemplate DataType="{x:Type local:AdministrativeEmployee}"> 
      <local:AdministrativeEmployeeView /> 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type local:FactoryEmployee}"> 
      <local:FactoryEmployeeView /> 
     </DataTemplate> 
    </ListBox.Resources>    
</ListBox> 

模型類:

public class Employee 
{ 
    public string Name { get; set; } 
} 

public class AdministrativeEmployee : Employee 
{ 
} 

public class FactoryEmployee : Employee 
{ 
} 

樣本數據:

List<Employee> _source = new List<Employee>(); 
_source.Add(new AdministrativeEmployee { Name = "A test1" }); 
_source.Add(new FactoryEmployee { Name = "F test1" }); 
_source.Add(new AdministrativeEmployee { Name = "A test2" }); 
_source.Add(new FactoryEmployee { Name = "F test2" }); 
Employees = _source; 

AdministrativeEmployeeView:

<UserControl ...> 
    <Grid> 
     <TextBlock Text="{Binding Name}" Background="Red" /> 
    </Grid> 
</UserControl> 

FactoryEmployeeView:

<UserControl ...> 
    <Grid> 
     <TextBlock Text="{Binding Name}" Background="Green" /> 
    </Grid> 
</UserControl> 

結果:

enter image description here

+0

這是非常接近我所需要的,反正,我必須要改變幾行 'xlmns:的ViewModels = 「CLR的命名空間:Solution.ViewModels」' 和改變的DataTemplates到: '