WPF Datagrid with some read-only rows - Stack Overflow
2021-03-23 00:25
I had the same problem. Using information provided in jsmith‘s answer and on Nigel Spencer‘s blog, I‘ve come up with a solution that doesn‘t require changing WPF DataGrid source code, subclassing or adding code to view‘s codebehind. As you can see, my solution is very MVVM Friendly.
It uses Expression Blend Attached Behavior mechanism so you‘ll need to install Expression Blend SDK and add reference to Microsoft.Expression.Interactions.dll, but this behavior could be easily converted to native attached behavior if you don‘t like that.
Usage:
...
ReadOnlyService.cs
using System.Windows;
namespace My.Common.Behaviors
{
internal class ReadOnlyService : DependencyObject
{
#region IsReadOnly
///
/// IsReadOnly Attached Dependency Property
///
private static readonly DependencyProperty BehaviorProperty =
DependencyProperty.RegisterAttached("IsReadOnly", typeof(bool), typeof(ReadOnlyService),
new FrameworkPropertyMetadata(false));
///
/// Gets the IsReadOnly property.
///
public static bool GetIsReadOnly(DependencyObject d)
{
return (bool)d.GetValue(BehaviorProperty);
}
///
/// Sets the IsReadOnly property.
///
public static void SetIsReadOnly(DependencyObject d, bool value)
{
d.SetValue(BehaviorProperty, value);
}
#endregion IsReadOnly
}
}
DataGridRowReadOnlyBehavior.cs
using System;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace My.Common.Behaviors
{
///
/// Custom behavior that allows for DataGrid Rows to be ReadOnly on per-row basis
///
internal class DataGridRowReadOnlyBehavior : Behavior
{
protected override void OnAttached()
{
base.OnAttached();
if (this.AssociatedObject == null)
throw new InvalidOperationException("AssociatedObject must not be null");
AssociatedObject.BeginningEdit += AssociatedObject_BeginningEdit;
}
private void AssociatedObject_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
var isReadOnlyRow = ReadOnlyService.GetIsReadOnly(e.Row);
if (isReadOnlyRow)
e.Cancel = true;
}
protected override void OnDetaching()
{
AssociatedObject.BeginningEdit -= AssociatedObject_BeginningEdit;
}
}
}
上一篇:WPF中获取形状范围
文章标题:WPF Datagrid with some read-only rows - Stack Overflow
文章链接:http://soscw.com/index.php/essay/67711.html