Wojtman
Wojtman

Reputation: 116

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?

Upvotes: 4

Views: 1092

Answers (2)

Cinchoo
Cinchoo

Reputation: 6322

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.

Upvotes: 3

ΩmegaMan
ΩmegaMan

Reputation: 31616

This assumes that myDataTable.DefaultView is a list of some objects(class instances).

So when the grid gets its ItemsSource set, it will then will present each row with one of the items from the list. So the binding to be specified will be a property/properties on the class.

So taking from your example template, if it is bound to a hypothetical list of person classes with FirstName and LastName on the class instance, one could set the template to bind to use those properties for each row like this:

 <StackPanel Orientation="Horizontal">
       <TextBlock Text="{Binding FirstName}"/>
       <TextBlock Text="{Binding LastName}"/>
       <Image/>
  </StackPanel>

Upvotes: 0

Related Questions