Thursday, January 12, 2023

Bindable read-only on XamDataGrid

I'm seeing colleagues binding the IsEnabled property of XamDataGrids. This prevents the user from editing the grid, but also prevents the grid from scrolling. This is not desirable. Infragistics recommends setting the AllowEdit property in the grid's FieldSettings but this is not bindable.

I created an attached property that will simulate a ReadOnly property but accesses the FieldSettings.AllowEdit property. It's really quite simple.

Create a class called ReadOnlyBehavior and set the content to this.

Imports System.Windows
Imports Infragistics.Windows.DataPresenter
 
Public Class ReadOnlyBehavior
    Inherits DependencyObject
 
    Public Shared ReadOnly ReadOnlyProperty As DependencyProperty =
        DependencyProperty.RegisterAttached("ReadOnly", GetType(Boolean), GetType(ReadOnlyBehavior),
                                            New PropertyMetadata(False, AddressOf ReadOnly_Changed))
 
    Public Shared Function GetReadOnly(o As DependencyObject) As Boolean
        Return Convert.ToBoolean(o.GetValue(ReadOnlyProperty))
    End Function
    Public Shared Sub SetReadOnly(o As DependencyObject, value As Boolean)
        o.SetValue(ReadOnlyProperty, value)
    End Sub
 
    Private Shared Sub ReadOnly_Changed(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim fs As FieldSettings
        If d.GetType().IsSubclassOf(GetType(XamDataGrid)) Then
            fs = DirectCast(d, XamDataGrid).FieldSettings
            If fs IsNot Nothing Then
                fs.AllowEdit = Not Convert.ToBoolean(e.NewValue)
            End If
        End If
    End Sub
End Class

In your XAML you will need a namespace such as 

xmlns:behaviors="clr-namespace:Behaviors"

and your XamDataGrid will need to attach the behavior like this

<XamDataGrid
behaviors:ReadOnlyBehavior.ReadOnly="{Binding IsGridReadOnly}"

</XamDataGrid>

Now your grid will be non-editable but still scollable.

No comments:

Post a Comment