简体   繁体   中英

wpf how to bind itemsource with CollectionViewSource

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?

i got it :

  <ListBox ItemsSource="{Binding CollectionViewSource.View}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

it works fine

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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM