CollectionViewSource如何在XAML中使用?

时间:2014-03-17 12:00:14

标签: .net wpf xaml binding collectionviewsource

在我的UserControl中有以下XAML,我在ListBox中看不到任何内容:

<UserControl x:Class="SampleProject1.AutoCompleteTextBox"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:SmartSender.NET"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
         mc:Ignorable="d" 
         d:DesignHeight="400" d:DesignWidth="600">
<UserControl.Resources>
    <x:Array Type="{x:Type sys:String}" x:Key="HTML5Tags">
        <sys:String>&lt;html&gt;</sys:String>
        <sys:String>&lt;body&gt;</sys:String>
        <sys:String>&lt;head&gt;</sys:String>
    </x:Array>
    <CollectionViewSource x:Key="X" Source="{StaticResource HTML5Tags}" />
</UserControl.Resources>
<Canvas>
    <Canvas.Resources>
        <DataTemplate x:Key="MyTemplate">
            <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                <Ellipse Width="7" Height="7" Fill="Blue" />
                <TextBlock Margin="6,0" FontFamily="Courier New" Height="16" 
                           Text="{TemplateBinding Content}" />
            </StackPanel>
        </DataTemplate>
    </Canvas.Resources>

    <TextBox Name="txt" Canvas.Left="0" Canvas.Top="0" KeyDown="txt_KeyDown"
             PreviewTextInput="txt_PreviewTextInput" />
    <ListBox Name="lst" Width="130" Height="120" Panel.ZIndex="1" 
             Visibility="Hidden" ItemTemplate="{StaticResource MyTemplate}" 
             ItemsSource="{StaticResource X.View}"
             KeyDown="lst_KeyDown" PreviewTextInput="lst_PreviewTextInput"/>
</Canvas>

我已尝试将XX.View都设为ItemsSource。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

所有Visibility

首先在listBox上设置为Hidden。删除它。

第二次如果在XAML中定义了CollectionViewSource,则无需绑定到View属性。当直接从XAML绑定时,WPF会在内部将CollectionViewSource转换为ICollectionView(在您的情况下为ListCollectionView

这是你在XAML中绑定的方式(注意你必须在绑定时设置Source而不是直接):

<ListBox Name="lst" Width="130" Height="120" Panel.ZIndex="1" 
         ItemTemplate="{StaticResource MyTemplate}" 
         ItemsSource="{Binding Source={StaticResource X}}"
         KeyDown="lst_KeyDown" PreviewTextInput="lst_PreviewTextInput"/>