i write a simpliest demo to bind listbox to CollectionViewSource, here is vm:
public class Model
{
public string Text { get; set; }
}
public partial class MainWindow : Window
{
public CollectionViewSource CollectionViewSource { get; set; }
public ObservableCollection<Model> Collection { get; set; }
public MainWindow()
{
InitializeComponent();
CollectionViewSource = new CollectionViewSource() { Source = GetSource() };
this.DataContext = this;
}
// get data
private ObservableCollection<Model> GetSource()
{
ObservableCollection<Model> models = new ObservableCollection<Model>();
models.Add(new Model() { Text = "a"});
models.Add(new Model() { Text = "b"});
models.Add(new Model() { Text = "c"});
models.Add(new Model() { Text = "d"});
return models;
}
}
xaml:
<ListBox ItemsSource="{Binding Source=CollectionViewSource.View}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
the result is not correct:
and if i delete datatemplate, xaml:
<ListBox ItemsSource="{Binding Source=CollectionViewSource.View}">
</ListBox>
it will be:
what's wrong with it? how can i bind my model's property to listbox?
CodePudding user response:
i got it :
<ListBox ItemsSource="{Binding CollectionViewSource.View}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
it works fine
CodePudding user response:
The expression
ItemsSource="{Binding Source=CollectionViewSource.View}"
sets the string literal "CollectionViewSource.View" as ItemsSource, which you noticed when you omitted the ItemTemplate.
Set the Binding's Path instead. CollectionViewSource
is a property of the current DataContext.
ItemsSource="{Binding Path=CollectionViewSource.View}"