How do you dynamically assign a datagrid's headers in c#?
How do you dynamically assign a datagrid's headers in c#?
Consider the following XAML:
<data:DataGrid x:Name="dataGrid" AutoGenerateColumns="False" Margin="1,1,1,1" >
<data:DataGrid.Columns>
<data:DataGridTextColumn
Header="Substantive"
Binding="{Binding Path=Substantive}"
IsReadOnly="True"
开发者_如何转开发/>
<data:DataGridTextColumn
Header=""
Binding="{Binding Path=Month[0]}"
IsReadOnly="True"
/>
<data:DataGridTextColumn
Header=""
Binding="{Binding Path=Month[1]}"
IsReadOnly="True"
/>
</data:DataGrid.Columns>
</data:DataGrid>
In the C# code, how would I define the headers that are blank?
OK, well, if no one knows, let's go with a different question. How does one create a DataGrid from scratch in C# code instead of in XAML?
You can add columns to a datagrid as such(for textcolumn):
text2 = new DataGridTextColumn();
bind = new System.Windows.Data.Binding("ValueList");
bind.ConverterParameter = i;
bind.Converter = new IndexConverter();
text2.Binding = bind;
text2.Header = "Header";
text2.MaxWidth = 100;
....
datagrid1.Columns.Add(text2);
You can allso access an existing column via:
((DataGridTextColumn)datagrid1.Columns[i]).Header = "Header";
Not sure what exactly you need but:
Creating new columns including header etc. see Do this in C# code instead of template XAML
change the header of a column see http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcolumn.header%28v=VS.95%29.aspx
Addressing your orignal question it would seem to me that a value converter would do the job here.
public class MyConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Do stuff with parameter, for example:-
int month = Convert.ChangeType(parameter, typeof(int), culture);
return cultrue.DateTimeFormat.GetAbbreviatedMonthName(month + 1);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then use it in your xaml:-
<UserControl.Resources>
<local:MyConverter x:Key="myconv" />
</UserControl.Resources>
...
<data:DataGrid x:Name="dataGrid" AutoGenerateColumns="False" Margin="1,1,1,1" >
<data:DataGrid.Columns>
<data:DataGridTextColumn
Header="Substantive"
Binding="{Binding Path=Substantive}"
IsReadOnly="True"
/>
<data:DataGridTextColumn
Header="{Binding Converter={StaticResource myconv} ConverterParameter=0}"
Binding="{Binding Path=Month[0]}"
IsReadOnly="True"
/>
<data:DataGridTextColumn
Header="{Binding Converter={StaticResource myconv} ConverterParameter=1}"
Binding="{Binding Path=Month[1]}"
IsReadOnly="True"
/>
</data:DataGrid.Columns>
</data:DataGrid>
When you use dataGrid.ItemsSource your DataGrid headers will be asigned to the names of variables in List you use as ItemsSource.
精彩评论