Search code examples
c#wpfdata-bindingdatagrid

Check if DataGrid ItemSource is populated via binding or assignment


Is there a way to find out (in code) if the ItemSource of the Datagrid was set via binding, or if there was an assignment?

Binding:

<DataGrid x:Name="MyGrid" ItemsSource="{Binding Foo}"/>

Assignment:

<DataGrid x:Name="MyGrid" />
MyGrid.ItemsSource = new List<int> { 1, 2, 3 };

Solution

  • there is a framework method to detect a Binding: BindingOperations.GetBindingExpression

    Returns the BindingExpression object associated with the given property or null if none exists

    var binding = BindingOperations.GetBindingExpression(MyGrid, DataGrid.ItemsSourceProperty);
    string result = (binding == null) ? "assignment" : "binding";