Binding WPF DataGrid to DataTable using TemplateColumns

Posted by Chris J on Stack Overflow See other posts from Stack Overflow or by Chris J
Published on 2010-04-20T17:55:07Z Indexed on 2010/04/21 22:33 UTC
Read the original article Hit count: 1142

Filed under:
|
|
|

I have tried everything and got nowhere so I'm hoping someone can give me the aha moment. I simply cannot get the binding to pull the data in the datagrid successfully.

I have a DataTable that contains multiple columns with of MyDataType}

public class MyData
{
    string nameData {get;set;}
    boolean showData {get;set;}
}

MyDataType has 2 properties (A string, a boolean) I have created a test DataTable

    DataTable GetDummyData()
    {
        DataTable dt = new DataTable("Foo");
        dt.Columns.Add(new DataColumn("AnotherColumn", typeof(MyData)));
        dt.Rows.Add(new MyData("Row1C1", true));
        dt.Rows.Add(new MyData("Row2C1", false));
        dt.AcceptChanges();
        return dt;
    }    

I have a WPF DataGrid which I want to show my DataTable. But all I want to do is to change how each cell is rendered to show [TextBlock][Button] per cell with values bound to the MyData object and this is where I'm having a tonne of trouble.

My XAML looks like this

            <Window.Resources><ResourceDictionary><DataTemplate x:Key="MyDataTemplate" DataType="MyData">
            <StackPanel Orientation="Horizontal" >
                <Button Background="Green" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="5,0,0,0" Content="{Binding Path=nameData}"></Button>
                <TextBlock Background="Green" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,0,0,0" Text="{Binding Path=nameData}"></TextBlock>
            </StackPanel>
        </DataTemplate></ResourceDictionary></Window.Resources>
        <Grid>
  <dg:DataGrid Grid.Row="1" AutoGenerateColumns="True" x:Name="dataGrid1" SelectionMode="Single" CanUserAddRows="False" CanUserSortColumns="true" CanUserDeleteRows="False" AlternatingRowBackground="AliceBlue"  AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn" ItemsSource="{Binding}" />

now all I do once loaded is to attempt to bind the DataTable to the WPF DataGrid

dt = GetDummyData();
dataGrid1.ItemsSource = dt.DefaultView;

The TextBlock and Button show up, but they don't bind, which leaves them blank. Could anyone let me know if they have any idea how to fix this. This should be simple, thats what Microsoft leads us to believe. I have set the Column.CellTemplate during the AutoGenerating event and still get no binding. Please help!!!

© Stack Overflow or respective owner

Related posts about wpf

Related posts about datagrid