Today i am building features using the new Datagrid for SL 4. Pretty cool.
I wanted to be able to set the column widths and headers magically in code. So i added names to the column headers like so:

<sdk:DataGrid x:Name="ErrorsDataGrid" HorizontalAlignment="Left" Margin="0,38,0,0" AutoGenerateColumns="False" >
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn x:Name="ErrorsGridMessageTextColumn" Binding="{Binding ErrorMessage}" Header="Message" Width="250*"/>
                <sdk:DataGridTextColumn x:Name="ErrorsGridID1TextColumn" Binding="{Binding UniqueID1}" Header="" />
                <sdk:DataGridTextColumn x:Name="ErrorsGridID2TextColumn" Binding="{Binding UniqueID2}" Header="" />
                <sdk:DataGridTextColumn x:Name="ErrorsGridID3TextColumn" Binding="{Binding UniqueID3}" Header="" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

Then created a few lines of code:

ErrorsGridID1TextColumn.Header = ID1Header;
ErrorsGridID1TextColumn.Width = new DataGridLength( Col1Width);

Exception!

Apparently even though i created the x:Name its not really being set to the column instance,.

Adding the next line above these two lines works as it sets the x:Name to the 2nd datagrid column:

ErrorsGridID1TextColumn = (DataGridTextColumn)ErrorsDataGrid.Columns[1];

Then i could reference it just fine.

Latest posts by Ken Spencer (see all)