【问题标题】:Disable Editing in rows if first Cell is empty for a datagrid in WPF如果 WPF 中的数据网格的第一个单元格为空,则禁用行中的编辑
【发布时间】:2017-08-23 05:53:14
【问题描述】:

我正在将 DataTable 绑定到 Datagrid。数据表中的列数和行数在运行时确定。但数据网格中显示的行数固定为 36。

因此,如果有时数据表有 ,则会显示空行以保持数据网格的高度。这样做的原因是我正在打印包含数据网格的网格,我不想弄乱打印模板的高度和宽度。

    <DataGrid x:Name="TestPointsDataGrid" ItemsSource="{Binding TestPointsTable,Mode=TwoWay}" HorizontalScrollBarVisibility="Disabled" 
CanUserResizeColumns="False" CanUserResizeRows="False" MouseRightButtonUp="DataGrid_MouseRightButtonUp"   
                                      CanUserAddRows="False" >

为了禁用我在样式触发器下面所做的第一列和最后一列:

    <Style TargetType="{x:Type DataGridCell}">
       <Style.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
             <Setter Property="Background" Value="Aqua"></Setter>
          </Trigger>
          <DataTrigger Value="Type" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
              <Setter Property="IsEnabled"  Value="false" />
              <Setter Property="FontWeight" Value="DemiBold"/>
           </DataTrigger>
           <DataTrigger Value="B or A" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
               <Setter Property="IsEnabled"  Value="false" />
               <Setter Property="FontWeight" Value="DemiBold"/>
               <Setter Property="Foreground" Value="Black"/>
            </DataTrigger>
       </Style.Triggers>
   </Style>

示例:

如上图所示,列数未知。 在我的情况下,第一列和最后一列始终是固定的。即分别为"Type""B or A"。我能够为这些列设置IsEnabled = false

如果第一列中有内容,则让用户编辑除第一列和最后一列之外的该行。 如何将那些空行的 IsEnabled 属性设置为 false ?或者只是任何解决方法来阻止用户在这些行中输入任何内容,除了不显示这些行。

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您最简单的做法是添加一个BeginningEdit 事件处理程序并在用户尝试编辑的行为空时取消编辑...

    <DataGrid x:Name="dataGrid" ItemsSource="{Binding PartCollection}" AutoGenerateColumns="True" BeginningEdit="dataGrid_BeginningEdit">
    
        private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            if((e.Row.Item as Part).Manufacturer == "XYZ")
            {
                e.Cancel = true;
            }
        }
    

    【讨论】:

    • PartMAnufacturer 在我的情况下是什么?在我的情况下,Datatable 中行的 DataType 是未知的。
    • 无论数据行在网格后面。您没有指出 TestPointsTable 是什么,所以我只是使用了我的一张表。如果 TestPointsTable 是 DataTable,则 e.Row.Item 将是 DataRowView。所以在这种情况下将是 (e.Row.Item as DataRowView).Row["Nominal"]
    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多