Search code examples
c#wpfxamldata-bindingvisual-studio-2015

How do I specify a DataGrid's ItemsSource type in XAML?


I'm binding a DataGrid to an ICollectionView so that I can filter the ItemsSource efficiently, but ICollectionView is not a generic type (as in CollectionView<MyType>) - it is of type List<object>. So in the XAML editor, VisualStudio can't determine what the type is, so I don't get any IntelliSense help binding to the properties of the object in the collection view. It still builds and runs, but I don't get the help at design time.

Rephrasing the question: Is there anyway to "cast" the data-binding in XAML?

I thought I could do something with <DataGrid.DataContext>, but I can't remember what it was and I haven't had any luck googling for it either:

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>

Code Behind:

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; }

    // ...
}

Solution

  • I thought I could do something with , but I can't remember what it was and I haven't had any luck googling for it either:

    I believe the setting the design time data context is that you are looking for. Please refer to the following links for more information about this.

    XAML: Intellisense for Bindings And the Data Context: https://blogs.msmvps.com/deborahk/xaml-intellisense-for-bindings-and-the-data-context/ How to see design-time data-binding in XAML editor (it works in runtime)?

    What I'm trying to ask is if there is any way to "cast" the data-binding as a collection of MyType in XAML?

    No. But you could specify a design-time DataContext as described above.