R. Savelyev
R. Savelyev

Reputation: 193

WPF. Is it possible to create DataGridTemplateColumn.CellTemplate with ComboBox and TextBox?

Now i have column with comboboxes in each row.

<DataGridTemplateColumn.CellTemplate>
       <DataTemplate >                      
            <ComboBox 
                ItemsSource="{Binding Path=PropertyDetails.ValidValues}" 
                SelectedItem="{Binding Path=CurrentValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                DisplayMemberPath="FullText">                                
            </ComboBox>
       </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>

And I need for example:
1st row - ComboBox
2nd row - TextBox
3rd row - TextBox
4th row - ComboBox

Upvotes: 0

Views: 768

Answers (2)

Petar Stojanovski
Petar Stojanovski

Reputation: 88

You can specify the columns pretty straightforward, as shown in the code below.

<DataGrid x:Name="dataGridName">
<DataGrid.Columns>
    <DataGridTextColumn x:Name="textBoxName" Header="TextBox Header"> 
    </DataGridTextColumn>
    <DataGridComboBoxColumn x:Name="comboBoxName" Header="Header Name">
    </DataGridComboBoxColumn>
    <DataGridTemplateColumn x:Name="templateName" Header="Template Header">
    </DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

Apart from textboxes and comboboxes, you can create templates, hyperlinks etc.

Upvotes: 2

Babbillumpa
Babbillumpa

Reputation: 1864

You could use a CellTemplateSelector....

Create a class that inherits from DataTemplateSelector:

public class YourTemplateSelector : DataTemplateSelector
{
  public DataTemplate ComboTemplate
  { get; set; }

  public DataTemplate TextTemplate
  { get; set; }

  public DataTemplate CheckTemplate
  { get; set; }

  public override DataTemplate SelectTemplate(object item, DependencyObject container)
  {
    MyObject obj = item as MyObject;

    if (obj != null)
    {
            // Select your template
    }
    else
      return base.SelectTemplate(item, container);
  }
}

Define the template inside your view:

<UserControl.Resources>
    <DataTemplate x:Key="ComboTemplate">
        <ComboBox ItemSource="{Binding}" />
    </DataTemplate>
    <DataTemplate x:Key="TextTemplate">
        <TextBlock Text="{Binding}" />
    </DataTemplate>
    <DataTemplate x:Key="CheckTemplate">
        <CheckBox IsChecked="{Binding}" />
    </DataTemplate> 
</UserControl.Resources>

And then use it:

<DataGridTemplateColumn Header="Your Custom Col">
    <DataGridTemplateColumn.CellTemplateSelector>
        <local:YourTemplateSelector 
            ComboTemplate="{StaticResource ComboTemplate}"
            TextTemplate="{StaticResource TextTemplate}"
            CheckTemplate="{StaticResource CheckTemplate}"/>
    </DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>

Upvotes: 2

Related Questions