WPF ListBox ItemsSource StaticResource / Pregunta de enlace
-
10-07-2019 - |
Pregunta
Dado el siguiente código:
<Window x:Class="WpfApplication76.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<CollectionViewSource x:Key="myCol">
<CollectionViewSource.Source>
<col:ArrayList>
<ListBoxItem>Uno</ListBoxItem>
<ListBoxItem>Dos</ListBoxItem>
<ListBoxItem>Tres</ListBoxItem>
</col:ArrayList>
</CollectionViewSource.Source>
</CollectionViewSource>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{StaticResource myCol}" />
<ListBox ItemsSource="{Binding Source={StaticResource myCol}}" />
</Grid>
</Window>
En este ejemplo, el
<ListBox ItemsSource="{StaticResource myCol}" />
Me da un error quejándose de que no se puede vincular a un " CollectionViewSource " objeto.
Pero el otro cuadro de lista:
<ListBox ItemsSource="{Binding Source={StaticResource myCol}}" />
se une perfectamente bien.
Entonces mi pregunta es ¿por qué uno funciona y el otro no? Al final, ¿no están ambos ItenSources configurados en el mismo " CollectionViewSource " objeto?
Gracias.
Solución
La propiedad ItemsSource es de tipo IEnumerable. Un CollectionViewSource no es un IEnumerable. La propiedad View de CollectionViewSource le dará un IEnumerable.
Cuando se enlaza a un CollectionViewSource, el enlace es lo suficientemente inteligente como para tomar la propiedad Ver y realmente enlazar a eso. Tal vez CollectionViewSource tiene una [DefaultBindingProperty] en ella.
Se reduce al hecho de que cuando pasas por el enlace, en realidad no lo haces al CollectionViewSource, sino a su propiedad View.