WPF Datagrid的一些只读行

问题描述 投票:13回答:3

我需要显示一些我的WPF Datagrid的行为只读或不依赖于我的绑定模型的属性。

如何才能做到这一点?

wpf datagrid wpftoolkit readonly
3个回答
21
投票

我有同样的问题。使用jsmith的答案,对佰斯宾塞的博客提供的信息,我想出了不需要改变WPF DataGrid的源代码,继承或添加代码来查看的代码隐藏的解决方案。正如你所看到的,我的解决方案是非常MVVM友好。

它采用Expression Blend Attached Behavior mechanism所以你需要安装的Expression Blend SDK,并添加引用Microsoft.Expression.Interactions.dll,但这种行为可以很容易地转换,如果你不喜欢,要native attached behavior

用法:

<DataGrid 
    xmlns:Behaviors="clr-namespace:My.Common.Behaviors"
...
>
    <i:Interaction.Behaviors>
         <Behaviors:DataGridRowReadOnlyBehavior/>
    </i:Interaction.Behaviors>
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsReadOnly}" Value="True"/>
                    <Setter Property="Behaviors:ReadOnlyService.IsReadOnly" Value="True"/>
                    <Setter Property="Foreground" Value="LightGray"/>
                    <Setter Property="ToolTipService.ShowOnDisabled" Value="True"/>
                    <Setter Property="ToolTip" Value="Disabled in ViewModel"/>
                </DataTrigger>

            </Style.Triggers>
        </Style>
      </DataGrid.Resources>
...
</DataGrid>

ReadOnlyService.cs

using System.Windows;

namespace My.Common.Behaviors
{
    internal class ReadOnlyService : DependencyObject
    {
        #region IsReadOnly

        /// <summary>
        /// IsReadOnly Attached Dependency Property
        /// </summary>
        private static readonly DependencyProperty BehaviorProperty =
            DependencyProperty.RegisterAttached("IsReadOnly", typeof(bool), typeof(ReadOnlyService),
                new FrameworkPropertyMetadata(false));

        /// <summary>
        /// Gets the IsReadOnly property.
        /// </summary>
        public static bool GetIsReadOnly(DependencyObject d)
        {
            return (bool)d.GetValue(BehaviorProperty);
        }

        /// <summary>
        /// Sets the IsReadOnly property.
        /// </summary>
        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
{
    /// <summary>
    /// Custom behavior that allows for DataGrid Rows to be ReadOnly on per-row basis
    /// </summary>
    internal class DataGridRowReadOnlyBehavior : Behavior<DataGrid>
    {
        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;
        }
    }
}

13
投票

我发现一对夫妇简单的解决方案这个问题。在我看来,最好是挂钩到DataGrid的BeginningEdit事件。这是类似于奈杰尔斯宾塞在他的岗位做了,但是你不必从数据网格覆盖它。该解决方案是伟大的,因为它不允许用户编辑任何行中的细胞,但它确实让他们选择行。

在代码背后:

private void MyList_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
  if (((MyCustomObject)e.Row.Item).IsReadOnly)  //IsReadOnly is a property set in the MyCustomObject which is bound to each row
  {
    e.Cancel = true;
  }
}

在XAML:

<DataGrid ItemsSource="{Binding MyObservableCollection}"
          BeginningEdit="MyList_BeginningEdit">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Name}"
                        Header="Name"/>
    <DataGridTextColumn Binding="{Binding Age}"
                        Header="Age"/>
  </DataGrid.Columns>
</DataGrid>

不同的解决方案......这不允许用户选择该行所有,但在代码中并不需要额外的代码后面。

<DataGrid ItemsSource="{Binding MyObservableCollection}">
  <DataGrid.Resources>
    <Style TargetType="{x:Type DataGridRow}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsReadOnly}"
                     Value="True" >
        <Setter Property="IsEnabled"
                Value="False" />   <!-- You can also set "IsHitTestVisble" = False but please note that this won't prevent the user from changing the values using the keyboard arrows -->
        </DataTrigger>

      </Style.Triggers>
    </Style>
  </DataGrid.Resources>

  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Name}"
                        Header="Name"/>
    <DataGridTextColumn Binding="{Binding Age}"
                        Header="Age"/>
  </DataGrid.Columns>
</DataGrid>

3
投票

我认为这样做最简单的方法是将IsReadOnly属性添加到DataGridRow类。这里是如何做到这一点here详细的文章奈杰尔·斯宾塞。

© www.soinside.com 2019 - 2024. All rights reserved.