I have a DataGrid, which is bound to a DataTable object. The user can press a special button, which will dynamically add new columns to this DataTable object. The AutoGenerateFields property in my DataGrid is set to false, because each column in this is styled column with a DataTemplate (each cell contains several TextBlocks).
I wrote the following style for my DataGrid:
<Style TargetType="{x:Type igDP:CellValuePresenter}" x:Key="YPStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">
<Grid Margin="4" Visibility="{Binding Path=DataItem.YPURL, Converter={StaticResource MyVisiblityConverter}}">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.RowSpan="2" Grid.Column="0"
FontWeight="DemiBold"
FontSize="18"
VerticalAlignment="Center"
Text="{Binding Path=DataItem.LYP}" x:Name="c"/>
<TextBlock Grid.Row="0" Grid.Column="1"
Foreground="{Binding Path=DataItem.RYP, Converter={StaticResource MyColorConverter}}"
Text="{Binding Path=DataItem.RYP}"
Margin="3, 0, 0, 0"
HorizontalAlignment="Right"
VerticalAlignment="Center"/>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center"
Grid.Row="0" Grid.Column="2"
HorizontalAlignment="Right"
Margin="8, 0, 0, 0">
<Image Source="../icons/icon_url.gif"
Cursor="Hand"/>
<Label Content="url"
Foreground="Blue"
Cursor="Hand"
ToolTip="{Binding Path=DataItem.YPU}"/>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You can see, that the TextBlocks are bound to some columns in DataTable: DataItem.LYP, DataItem.YPU.
The problem is finding a dynamic way to set that binding. When the user adds new columns to a bound DataTable object, I creates a new column in my DataGrid with this style. But how can I dynamically set different values for Text properties for my TextBlock in this style?
For example, first column in my DataGrid is bound to Column_1, Column_2, Column_3 in DataTable. When the user presses “Add new column”, program creates 3 new columns in the DataTable object with names “Column_4”, “Column5″, Column 6” and creates new column in the DataGrid with this style. But how can I set binding for second column to new columns in the DataTable?
Thanks a lot.
Now I use style wich was creating in code behind. It’s working!
Thanks all.