考虑以下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没有绑定,它是空的。
这两个绑定有什么区别?
答案 0 :(得分:6)
首先,要使用第二个选项,您需要绑定CollectionViewSource.View
属性。
<DataGrid ItemsSource="{Binding ItemsViewSource.View}" />
当您将dataGrid的DataContext绑定到CollectionViewSource时, dataGrid会在内部执行从CollectionViewSource到ICollectionView(在您的情况下为ListCollectionView) 的值转换,但是当您明确要求它绑定到CollectionViewSource,它不进行默认值转换。您可以通过将转换器放入绑定中来验证这一点。