renatogbp renatogbp - 1 month ago 12
C# Question

Is it possible to edit only one control in DataGridTemplateColumn?

I have done some research but did not find an answer for my question. There it is: I have a DataGridTemplateColumn which takes a StackPanel and two TextBlocks inside. I want to be able to edit one of the TextBlock only, is it possible?

there is my code:

<DataGrid Name="gdProducts"
MinHeight="100"
ItemsSource="{Binding ProductsView, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedProduct, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False"
GridLinesVisibility="None"
IsSynchronizedWithCurrentItem="False"
CanUserAddRows="False"
CanUserDeleteRows="False">
<DataGrid.Columns>

<!-- other columns -->

<DataGridTemplateColumn Header="Waiting Period"
IsReadOnly="False"
Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding WaitingPeriod}"/>
<TextBlock Text=" days"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

</DataGrid.Columns>
</DataGrid>


The way the code is written I will edit both TextBlocks (whole StackPanel). That is not I want.

Thanks!

EDIT

Sorry for my mistake, actually my code above does not allow me to edit anything at all. I thought the IsReadOnly set to False would allow it to be editable like the others DataGrid Column types.

Rom Rom
Answer

just use TextBox instead of TextBlock to the property you want to edit:

  <StackPanel Orientation="Horizontal">
         <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.WaitingPeriod}"/>
         <TextBlock Text=" days"/>
   </StackPanel>

The RelativeSource is taking you up the visual tree to DataGrid, and the DataGrid DataContext is your ViewModel and this is why you have Access to WaitingPeriod propery.