angel
angel

Reputation: 332

apply a template to a column of datagrid

I'm using MVVM and I want to apply a template to a specific column of my datagrid.

I create Machine class which have Name, costs, properties.

I create also Operation Class which have Name porperty, ExecutiveMachine property (Type : Machine) When I use itemsSource to display my list of opertations, I see the path of my machines whereas I want to display their name. I added DataGridTemplateColumn but now, I have machine column twice (one correct, and the other is incorrect)

Actually my code is :

<DataGrid ItemsSource="{Binding Path=Operations}" Name="datagridOperation" Width="Auto" Height="Auto" Margin="10" HorizontalContentAlignment="Center" SelectionMode="Single" MinColumnWidth="80" CanUserAddRows="False" CanUserDeleteRows="False" RowBackground="DimGray" AlternatingRowBackground="#FF3E3E3E" AlternationCount="1" IsReadOnly="True" SelectionChanged="UpdateOperationComboBox">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Machine" CanUserSort="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Label Content="{Binding Path=ExecutiveMachine.Name}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
  </DataGrid>

My first idea was to add manually DataGridColumns. I tried it but when a do it i have twice all my columns and if I delete ItemsSource property of my DataGrid I have only once but the three columns become empty. If my idea is good, how can I bind this ItemsSource ?

Upvotes: 0

Views: 318

Answers (1)

dkozl
dkozl

Reputation: 33394

If you want to add you columns manually then you need to switch off AutoGenerateColumns against your DataGrid

<DataGrid 
    ItemsSource="{Binding Path=Operations}" 
    Name="datagridOperation"
    ...
    AutoGenerateColumns="False">

EDIT

To manually define sorting path for any DataGridColumn you can specify DataGridColumn.SortMemberPath

<DataGridTemplateColumn Header="Machine" CanUserSort="True" SortMemberPath="SortPropertyName">

Upvotes: 2

Related Questions