The following DataGrid is set to ReadOnly. But, when Edit Button on a row is clicked I need that row to become editable. How can we achieve this task?
Please note that the Edit button click event is still fired on a ReadOnly grid. Maybe, in this event we need to set DataGridCell.IsEditing Property to true for each cell on that row. But I am not able to get the DataGridCell object in the row. Or, there may be some better options.
<Window x:Class="MyTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
.....
Title="MainWindow">
<Grid>
<DataGrid x:Name="MyDatagrid" IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Single">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Edit">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="btnEdit" Content="Edit" Click="btnEdit_Click"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" Visibility="Collapsed" Binding="{Binding MyClassId}" />
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
MyClass and other relevant code:
public class MyClass
{
[Key]
public int MyClassId { get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
.........
.........
}
//DataGrid binding to source:
List<MyClass> lstMyClass = db.MyClass.ToList();
MyDatagrid.ItemsSource = lstMyClass;
............
.........
First, Each Column Must Have IsReadOnly.
And IsReadOnly Binding MyClass's Is_Checked.
ToggleButton's IsChecked Binding MyClass's Is_Checked,too.
Then, When ToggleButton Click , Change Column's IsReadOnly.
All of this should be MVVM