Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind TextBlock.Text in DataGridCell template using ItemsSource

I want to have DataGridCell with text and image.
Currently, my code looks like that

XAML:

<DataGrid Name="myDataGrid" CellStyle="{StaticResource myCellStyle}" />

Style:

<Style x:Key="myCellStyle" TargetType="DataGridCell">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding}"/>
                    <Image/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

C#:

myDataGrid.ItemsSource = myDataTable.DefaultView;

The question is:
How to bind text to a TextBlock using ItemsSource?

like image 472
Wojtman Avatar asked Sep 04 '25 02:09

Wojtman


1 Answers

You must do couple of things to fix it

First, set 'AutoGenerateColumns' to true

<DataGrid CellStyle="{StaticResource myCellStyle}" AutoGenerateColumns="True">

Next in your cell style

<Style x:Key="myCellStyle" TargetType="DataGridCell">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                        Path=Content.Text}"/>
                    <Image/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Hope this helps.

like image 86
Cinchoo Avatar answered Sep 06 '25 16:09

Cinchoo