【问题标题】:My listview items are not showing up when setting a template for it为其设置模板时,我的列表视图项目未显示
【发布时间】:2012-10-02 13:05:08
【问题描述】:

我有两个模板,一个用于文本框,一个用于列表视图,两者都只是用来给它们圆角而不是默认矩形。我的文本框需要“ScrollViewer x:Name="PART_ContentHost" 行才能显示文本,但这不适用于列表视图。如果我取出列表视图的模板,则会显示示例列表视图项(东西)。否则它不会,而且我看不到我在后面的代码中添加的任何其他项目。我在 xaml 中缺少什么来让它工作?

下面是我的 xaml:

   <!-- Design Templates to set the borders of the controls-->
<UserControl.Resources>
    <ControlTemplate x:Key="TextBoxTemplate" TargetType="TextBox">
        <Border BorderBrush="Black" BorderThickness="1,1,1,.5" CornerRadius="7">
            <ScrollViewer x:Name="PART_ContentHost" ></ScrollViewer>
        </Border>
    </ControlTemplate>
    <ControlTemplate x:Key="ListViewTemplate" TargetType="ListView">
        <Border BorderBrush="Black" BorderThickness=".5,1,1,1" CornerRadius="7">
        </Border>
    </ControlTemplate>
</UserControl.Resources>

<!-- Controls -->
<Grid Height="270" Width="400">
    <StackPanel Width="390">
        <TextBox Height="35" Name="InputTextbox" Template="{StaticResource TextBoxTemplate}" VerticalContentAlignment="Center" TextChanged="InputTextbox_TextChanged"></TextBox>
        <ListView Height="235" Name="ResultsListView" Template="{StaticResource ListViewTemplate}"  SelectionChanged="ResultsListView_SelectionChanged">
            <ListViewItem Content="stuff"></ListViewItem>
        </ListView>
    </StackPanel>
</Grid>

【问题讨论】:

  • 您的ListView 模板中缺少ContentPresenter。我猜你的TextBox 不需要它,因为它可能是为了将其内容放在名为PART_ContentHost 的组件中而构建的。

标签: c# wpf templates listview controls


【解决方案1】:

您的 ControlTemplate 没有与之关联的演示者。这就是您没有看到任何项目的原因。有关如何创建 ListView.ControlTemplate 的工作示例,请参阅此页面:

MSDN: ListView ControlTemplate Example

这是您的控件模板的更新 xaml:

<ControlTemplate x:Key="ListViewTemplate" TargetType="ListView">
    <Border BorderBrush="Black" BorderThickness=".5,1,1,1" CornerRadius="7">
      <ScrollViewer>
        <ItemsPresenter />
      </ScrollViewer>
    </Border>
</ControlTemplate>

【讨论】:

  • 非常感谢!这正是我所缺少的。我在任何地方都找不到该文档,谷歌也帮不上忙 :( 如此简单的解决方案,否则我永远找不到,谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 2023-03-14
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多