WPF将DataGrid绑定到CollectionViewSource:通过DataContext工作,通过ItemsSource清空;区别?

时间:2015-02-03 12:37:08

标签: wpf data-binding datagrid datacontext itemssource

考虑以下XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c="clr-namespace:WpfApplication1"
    DataContext="{Binding Source={x:Static c:ViewModel.Instance}}"
    >
<Grid>
    <DataGrid DataContext="{Binding ItemsViewSource}" ItemsSource="{Binding}" />

</Grid>

和视图模型:

public class ItemViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ViewModel
{
    public static ViewModel Instance { get; set; }

    static ViewModel()
    {
        Instance = new ViewModel();
    }

    public ObservableCollection<ItemViewModel> Items { get; private set; }
    public CollectionViewSource ItemsViewSource { get; private set; }

    public ViewModel()
    {
        Items = new ObservableCollection<ItemViewModel>();
        ItemsViewSource = new CollectionViewSource() { Source = Items };
        Items.Add(new ItemViewModel() { FirstName = "test", LastName = "test" });
    }
}

此代码正常,但如果我更改

<DataGrid DataContext="{Binding ItemsViewSource}" ItemsSource="{Binding}" />

<DataGrid ItemsSource="{Binding ItemsViewSource}" />`

DataGrid没有绑定,它是空的。

这两个绑定有什么区别?

1 个答案:

答案 0 :(得分:6)

首先,要使用第二个选项,您需要绑定CollectionViewSource.View属性。

<DataGrid ItemsSource="{Binding ItemsViewSource.View}" />

当您将dataGrid的DataContext绑定到CollectionViewSource时, dataGrid会在内部执行从CollectionViewSource到ICollectionView(在您的情况下为ListCollectionView) 的值转换,但是当您明确要求它绑定到CollectionViewSource,它不进行默认值转换。您可以通过将转换器放入绑定中来验证这一点。