Mussammil
Mussammil

Reputation: 894

wpf toggle datagridcell read-only

I have a datagrid with one column namely Qty ,where the user can enter qty only (editable) when the user press the Edit button on the form other wise its stand like read only field.

How to accomplish this?

Upvotes: 0

Views: 780

Answers (2)

Sheridan
Sheridan

Reputation: 69985

If you use a CheckBox or ToggleButton then you can do this with just a Binding without requiring any code behind:

<ToggleButton Name="EditButton" Content="Edit" />
...
<DataGrid ItemsSource="{Binding YourCollection}">
    <DataGrid.Columns>
        ...
        <DataGridTextColumn Header="Quantity" IsReadOnly="{Binding IsChecked, 
            ElementName=EditButton}" Binding="{Binding Quantity}" />
        ...
    </DataGrid.Columns>
</DataGrid>

UPDATE >>>

If you use a class to display your items in the DataGrid (which is always a good idea), then there is a simple solution. You can just add an extra bool property to Bind to the IsReadOnly property and you can update the bool value each time the Quantity property is changed:

public string SerialNo
{
    get { return serialNo; } 
    set
    {
        serialNo = value;
        NotifyPropertyChanged("SerialNo");
        // Update new property
        IsQtyReadOnly = serialNo == "The read only value";
    }
}

public bool IsQtyReadOnly // <<< New property
{
    get { return isQtyReadOnly; } 
    set { isQtyReadOnly= value; NotifyPropertyChanged("IsQtyReadOnly"); }
}

And the XAML:

<ToggleButton Name="EditButton" Content="Edit" />
...
<DataGrid ItemsSource="{Binding YourCollection}">
    <DataGrid.Columns>
        ...
        <DataGridTextColumn Header="Qty" IsReadOnly="{Binding IsQtyReadOnly}" 
            Binding="{Binding Qty}" />
        ...
    </DataGrid.Columns>
</DataGrid>

If you do it this way, the IsQtyReadOnly property will automatically update whenever the SerialNo property value changes.

Upvotes: 1

hbsrud
hbsrud

Reputation: 353

You need an Event-Handler for that Button:

private void OnClick(object sender, RoutedEventArgs e)
{
    QtyColumn.IsReadOnly = !QtyColumn.IsReadOnly;
}

Upvotes: 0

Related Questions