如何在 XAML 中指定 DataGrid 的 ItemsSource 类型?

问题描述 投票:0回答:3

我将

DataGrid
绑定到
ICollectionView
,以便我可以有效地过滤 ItemsSource,但是
ICollectionView
不是 generic 类型(如
CollectionView<MyType>
中所示) - 它属于
List<object> 类型
。因此,在 XAML 编辑器中,VisualStudio 无法确定类型是什么,因此我没有得到任何绑定到集合视图中对象属性的 IntelliSense 帮助。它仍然可以构建并运行,但我在设计时没有得到帮助。

重新表述问题:是否有办法在 XAML 中“强制转换”数据绑定?

我以为我可以用

<DataGrid.DataContext>
做点什么,但我不记得那是什么了,而且我也没有在谷歌上搜索它:

XAML:

<DataGrid ItemsSource="{Binding MyCollectionView}">
    <DataGrid.DataContext>
        <!-- Specify the type of objects in MyCollectionView somehow -
                 something like 'x:type="MyType"' -->
    </DataGrid.DataContext>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <!-- Cannot resolve property 'Approved' in data context of type 'MyProject.MainWindow'. -->
                <DataTrigger Binding="{Binding Approved}" Value="False">
                    <Setter Property="Background" Value="LightGray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <DataGrid.Columns>
        <!-- Cannot resolve property 'Approved' in data context of type 'object'. -->
        <DataGridTextColumn Header="Is Approved"
                            Binding="{Binding Approved}"
                            Width="3*" />
    </DataGrid.Columns>
</DataGrid>

背后代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public ICollectionView MyCollectionView { get; set; }

    public MainWindow(List<MyType> parameter)
    {
        // ...

        MyCollectionView = new CollectionView(parameter);

        // ...
    }
}

public class MyType
{
    public bool Approved { get; set; }

    // ...
}
c# wpf xaml data-binding visual-studio-2015
3个回答
4
投票

我以为我可以用 做点什么,但我不记得那是什么,而且我也没有运气用谷歌搜索它:

我相信设置设计时数据上下文正是您正在寻找的。请参阅以下链接了解更多相关信息。

XAML:用于绑定和数据上下文的智能感知:https://blogs.msmvps.com/deborahk/xaml-intellisense-for-bindings-and-the-data-context/ 如何在 XAML 编辑器中查看设计时数据绑定(它在运行时工作)?

我想问的是是否有任何方法可以将数据绑定“转换”为 XAML 中的 MyType 集合?

不。但是您可以如上所述指定设计时 DataContext。


0
投票

VisualStudio 无法确定类型是什么

由于类型直到运行时才表达并通过代码使用反射来获取,因此设计者处于不利地位,只能根据其所知进行推断。它所知道的是它是一个

object
,但不是开发人员知道的精确类型。

我没有得到任何 IntelliSense 帮助...仍然可以构建和运行,但我在设计时没有得到帮助

如果这是阻碍您的问题,我建议您暂时将相关属性类型的列表添加到 VM(如果不是 MVVM,则添加到页面),然后绑定到该新属性。然后设计时间将看到它需要什么,并且您可以在 Visual Studio 的帮助下获取属性信息添加绑定/样式。

一旦一切顺利,将设计时绑定替换为您提到的

ICollection


0
投票

一种解决方案是将

View
绑定到
ObservableCollection
,但仍然使用 ICollectionView 中的底层
default
GetDefaultView()
实例(可以使用
ViewModel
获取)来设置过滤、分组、等等。由于
View
实际上绑定到此 default
ICollectionView
,因此您在
ICollectionView
上设置的过滤和分组将正常工作,而设计器将有足够的信息来启用 IntelliSense(因为
ObservableCollection
是通用的) .

对于大多数情况,这已经足够了(假设您没有创建

ICollectionView
的单独实例)。

© www.soinside.com 2019 - 2024. All rights reserved.