[英]wpf how to bind itemsource with CollectionViewSource
i write a simpliest demo to bind listbox to CollectionViewSource, here is vm:我编写了一个最简单的演示来将列表框绑定到 CollectionViewSource,这里是 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: xml:
<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:如果我删除数据模板,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.将字符串文字“CollectionViewSource.View”设置为 ItemsSource,您在省略 ItemTemplate 时会注意到这一点。
Set the Binding's Path instead.改为设置绑定路径。
CollectionViewSource
is a property of the current DataContext. CollectionViewSource
是当前 DataContext 的一个属性。
ItemsSource="{Binding Path=CollectionViewSource.View}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.