Search code examples
c#wpfdata-binding

unable to cast MS.Internal.NamedObject


<DataGrid x:Name="DisplayRecipeGrid" AutoGenerateColumns="False" CanUserAddRows="false" ItemsSource="{Binding ModuleRecipeCatalog}"   VerticalContentAlignment="Center" IsReadOnly="True">
    <!---->
                                            <DataGrid.RowStyle>
                                                <Style TargetType="{x:Type DataGridRow}">
                                                    <EventSetter Event="MouseDoubleClick" Handler="EditRecipe_Executed"></EventSetter>
                                                </Style>
                                            </DataGrid.RowStyle>
                                            <DataGrid.Columns>
            <DataGrid x:Name="DisplayRecipeGrid" AutoGenerateColumns="False" CanUserAddRows="false" ItemsSource="{Binding ModuleRecipeCatalog}"   VerticalContentAlignment="Center" IsReadOnly="True"><!---->
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <EventSetter Event="MouseDoubleClick" Handler="EditRecipe_Executed"></EventSetter>
        </Style>
    </DataGrid.RowStyle>
    </DataGrid.Columns>
</DataGrid>

After using CanUserAddRows="false", when I manipulate a data.

Ended up with error stating unable to cast MS.Internal.NamedObject.

Tried with below approach, it worked:

if (obj.GetType().ToString() != "MS.Internal.NamedObject")
    return this.Equals(obj as RecipeBase);
else
    return false;

Can anyone have any other approach?


Solution

  • Can anyone have any other approach?

    You should use the as operator and check the result to determine whether the cast succeeded:

    RecipeBase x = obj as RecipeBase;
    if(x == null)
        return false;
    
    return Equals(x);
    

    Then there is no need to compare the string representation of the object's type with "MS.Internal.NamedObject".

    If you still want to do this for some strange reason, it's probably nicer to compare with the System.Windows.Data.CollectionView.NewItemPlaceholder constant:

    if(!(obj is System.Windows.Data.CollectionView.NewItemPlaceholder))