Scott Harrison - The golden apples
Henry Parker's Robot Wars

ASP.Net, ADO, MS Access
C# How to add data to a WPF dataGrid using an ObservableCollection

C# How to add data to a WPF dataGrid using an ObservableCollection

(26 hits)
Overview: Hits=10 In this code snippet, I demonstrate how to use WPF XAML to display "Is A" data in one datagrid and "Has A" data in another datagrid for the dog class (see How to create concrete classes with polymorphism). XAML allows the developer to place wpf controls within a Grid or a Canvas. The grid allows the window to be partition into rows and columns. In this case there is only one row and one column by default for the grid. Within the grid is a combobox control with three values: Dog, Cat and Horse. Two data grids are defined within the grid relative position to the row top and column left position, they reside in. The dataGridIsA has one column which is data bound to an observable collection with the class field name of "IsAString".

An ObservableCollection is a dynamic collection of objects of a given type. The IsA observableCollection contains data attributes of both the mammal abstract class and the dog class either from the ICollection or method calls. Additionally, the dataGridHasA is data bound to the observable collection holding the IsA ICollection attributes of the dog class. The AutoGenerate attribute of the dataGrid is set to false preventing the application from creating a data grid column from the observablecollection class variable names.

Hits=16 When objects are added, removed, or updated from the ObservableCollection the dataGrid is automatically updated with those changes. WPF adds a CollectionChanged event handler to the ObservableCollection's events.

XAML

<Window x:Class="Mammals.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Mammals"
        mc:Ignorable="d"
        Title="MainWindow">

    <Grid>

        <ComboBox x:Name="cboMammalType" HorizontalAlignment="Left" Margin="154,46,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="cboMammalType_SelectionChanged" Height="33" RenderTransformOrigin="0.5,0.5">
            <ComboBoxItem Content="Dog" HorizontalAlignment="Left" Width="118.4"/>
            <ComboBoxItem Content="Cat" HorizontalAlignment="Left" Width="118.4"/>
            <ComboBoxItem Content="Horse" HorizontalAlignment="Left" Width="118.4"/>
        </ComboBox>

        <Button x:Name="cmdForm" Content="Launch Form" HorizontalAlignment="Left" Margin="154,107,0,0" VerticalAlignment="Top" Width="120" Height="32" Click="cmdForm_Click"/>
        <DataGrid x:Name="dataGridIsA" HorizontalAlignment="Left" Margin="307,46,0,0" VerticalAlignment="Top" Height="178" Width="214" SelectionChanged="dataGridIsA_SelectionChanged">

            <DataGrid.Columns>
                <DataGridTextColumn Width="*" Header="Is A" Binding="{Binding IsAString}"/>
            </DataGrid.Columns>

        </DataGrid>
        <DataGrid x:Name="dataGridHasA" HorizontalAlignment="Left" Margin="538,46,0,0" VerticalAlignment="Top" Height="178" Width="214">
            <DataGrid.Columns>
                <DataGridTextColumn Width="*" Header="Has A" Binding="{Binding HasAString}"/>
            </DataGrid.Columns>
        </DataGrid>


    </Grid>
</Window>

C# Code

   

  private void cboMammalType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cboMammalType.SelectedItem.ToString().Contains("Dog"))
            {

                Dog dog = new Dog(new
                {
                    Breed = "German Sheppard",
                    Sex = "Female",
                    Color = "Brown",
                    Age = 1
                }
                ,
                new List<string>(new string[] {
                "Tail",
                "Two Ears",
                "Loud Bark",
                "Soft Fur"
                })
                );

                //Dog dog = new Dog();
                System.Collections.ObjectModel.ObservableCollection<object> dataListIsA = new System.Collections.ObjectModel.ObservableCollection<object>();
                System.Collections.ObjectModel.ObservableCollection<object> dataListHasA = new System.Collections.ObjectModel.ObservableCollection<object>();


//*******************************Is A******************************//
                dynamic data = null;

                data = new { IsAString = "Mammal Warm Blooded=" + dog.IsWarmBlooded().ToString() };dataListIsA.Add(data);

                Mammal mammal = dog;
                 
                foreach (var item in mammal.IsA)
                {
                    data = new { IsAString = item };  dataListIsA.Add(data);
                }
                dynamic IsA = dog.IsA;
                data = new {IsAString = "Breed=" + IsA.Breed}; dataListIsA.Add(data);
                data = new { IsAString = "Sex =" + IsA.Sex }; dataListIsA.Add(data);
                data = new { IsAString = "Color =" + IsA.Color}; dataListIsA.Add(data);
                data = new { IsAString = "Age =" + IsA.Age}; dataListIsA.Add(data);

                data = new { IsAString = "Dog Pack Hunter=" + dog.IsAPackHunter().ToString() }; dataListIsA.Add(data);
                data = new { IsAString = "Dog is a puppy=" + dog.IsAPuppy().ToString() }; dataListIsA.Add(data);

                dataGridIsA.AutoGenerateColumns = false;
                dataGridIsA.ItemsSource = dataListIsA;

//*******************************Has A******************************//

                data = new  { HasAString = "Dog sound" + dog.GetSound()}; dataListIsA.Add(data);
               
                foreach (var item in dog.HasA)
                {
                    data = new { HasAString = item };
                    dataListHasA.Add(data);
                }
                dataGridHasA.AutoGenerateColumns = false;
                dataGridHasA.ItemsSource = dataListHasA;
            }
        }

In short, I have demonstrated how to load an observable collection of dynamic data objects. The dataGrid and the observable collection implement two way binding through built in wpf functions.....

...<<<Register to correspond>>> ...

Members : 152
Name:
Email:

Register to View

Help