另一个UserControl中的ItemTemplate定义

时间:2015-09-28 08:27:28

标签: c# wpf user-controls

我有以下usercontrol来定义我的通用控件布局:

<UserControl>
    <DockPanel LastChildFill="False">
        <ListView DockPanel.Dock="Left"
                  ItemsSource="{Binding FoundResults}"
                  SelectedItem="{Binding SelectedItem}"
                  ItemTemplate="{DynamicResource FoundResultsStyle}"/>
        <ContentControl DockPanel.Dock="Top"
                        Name="WinSock"
                        Content="{Binding ElementName=BaseWindowUserControl, Path=SpecificView}" />
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem Content="{Binding StatusBarText, Mode=OneWay}" />
        </StatusBar>
    </DockPanel>
</UserControl>

如您所见,每个窗口左侧都应有一个ListView。

我需要一种在具体的userControl中定义ItemTemplate的方法。

与人用户控件:

<UserControl.Resources>
    <DataTemplate x:Key="FoundResultsStyle" DataType="{x:Type Pocos:Person}">
       <StackPanel>
            <TextBlock Text="{Binding Lastname}"/>
            <TextBlock Text="{Binding Firstname}"/>
       </StackPanel>
    </DataTemplate>
</UserControl.Resources>

ListView不使用我在“具体”用户控件中定义的模板。有没有办法实现这个目标?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情,以便DataType在更改时会选择正确的模板吗?

<UserControl>

    <UserControl.Resources> 
        <DataTemplate DataType="{x:Type Pocos:Person}"> 
             ...
        </DataTemplate>
        <DataTemplate DataType"{x:Type Pocos:Dog}">
            ...
        </DataTemplate>
    </UserControl.Resources>


    <DockPanel LastChildFill="False">
        <ListView 
          DockPanel.Dock="Left"
          ItemsSource="{Binding FoundResults}"
          SelectedItem="{Binding SelectedItem}"/>
        <ContentControl 
          DockPanel.Dock="Top"
          Name="WinSock"
          Content="{Binding ElementName=BaseWindowUserControl, Path=SpecificView}" />
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem Content="{Binding StatusBarText, Mode=OneWay}" />
        </StatusBar>
    </DockPanel>

</UserControl>