WPF 将 DataGrid 绑定(bind)到 CollectionViewSource : working via DataContext, 通过 ItemsSource 为空;不同之处?

标签 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>

和 View 模型:

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 没有绑定(bind),它是空的。

这两个绑定(bind)有什么区别?

最佳答案

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

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

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

关于WPF 将 DataGrid 绑定(bind)到 CollectionViewSource : working via DataContext, 通过 ItemsSource 为空;不同之处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299148/

相关文章:

c# - 在不同行中添加具有不同值的 DataGrid 复选框列

c# - 具有自定义和默认先决条件的 Clickonce WPF 应用程序

c# - 将消息传递给Caliburn Micro中的静态类

c# - 更改对象值时不刷新 DataContext

asp.net - 为什么这个 DropDownList 数据绑定(bind)到 List<String> 不起作用?

c# - 为什么我的绑定(bind)只能以一种方式工作?

c# - WPF DataGrid 选定的单元格更改为 "The current value of the SelectionUnit property on the parent DataGrid prevents rows from being selected."

c# - 如何从 ResourceDictionary 设置 Button.Command?

wpf - 在wpf中添加图标字体

c# - wpf:如何弹出用户控件?