Question

Having the following XAML in my UserControl, I don't see anything in the 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>

I have tried with both X and X.View as ItemsSource. What am I doing wrong here?

Was it helpful?

Solution

First of all Visibility is set to Hidden on your listBox. Remove that.

Second you need not to bind to View property if CollectionViewSource is defined in XAML. WPF internally convert CollectionViewSource to ICollectionView (ListCollectionView in your case) when binded directly from XAML.

This is how you bind in XAML (Notice you have to set Source on binding and not directly):

<ListBox Name="lst" Width="130" Height="120" Panel.ZIndex="1" 
         ItemTemplate="{StaticResource MyTemplate}" 
         ItemsSource="{Binding Source={StaticResource X}}"
         KeyDown="lst_KeyDown" PreviewTextInput="lst_PreviewTextInput"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top