12

如何在只读数据网格中使一列可编辑?

<DataGrid x:Name="dgLoadDtl" Height="315" Width="710" Grid.Row="0" 
                  HorizontalAlignment="Left" VerticalAlignment="Bottom"  
                  Style="{DynamicResource StyleDatagrid}" 
                  IsReadOnly="true">

            <DataGrid.Columns>                    

                <DataGridTextColumn Foreground="Black" Width="60" Header="Sctn" Binding="{Binding Sctn, Mode=TwoWay}" IsReadOnly="false" />                    
                <DataGridTextColumn Foreground="Black" Width="140" Header="CustName"  Binding="{Binding CustName, Mode=TwoWay}" />
                <DataGridTextColumn Foreground="Black" Width="140" Header="Address"  Binding="{Binding Address1, Mode=TwoWay}" />
                <DataGridTextColumn Foreground="Black" Width="50" Header="Bulk   or Bag"  Binding="{Binding BulkorBag, Mode=TwoWay}" />
                <DataGridTextColumn Foreground="Black" Width="80" Header="ProdCode" Binding="{Binding ProdCode, Mode=TwoWay}" />
                <DataGridTextColumn Foreground="Black" Width="80" Header="MedCode" Binding="{Binding MedCode, Mode=TwoWay}" />

4

1 回答 1

16

我创建了一个示例,我将 DataGrid 的 ItemsSource 绑定到 ObservableCollection,从这里您有两个选项。

  1. 在 DataGrid 上设置 AutoGenerateColumns="False" 并为除要编辑的列之外的所有列设置 IsReadOnly="True",您将设置 IsReadOnly="False"。
  2. AutoGenerateColumns="True"(这是默认设置,因此您可以从 XAML 中删除该属性)并在您的 ViewModel 中将设置器设为私有,用于除您希望可编辑的列之外的所有属性。

这是选项 1 的示例代码:

<DataGrid x:Name="dgLoadDtl" Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding MyData}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Foreground="Black" Width="60" Header="Sctn" Binding="{Binding Sctn, Mode=TwoWay}" IsReadOnly="false" />
        <DataGridTextColumn Foreground="Black" Width="140" Header="CustName"  Binding="{Binding CustName, Mode=TwoWay}" IsReadOnly="True"/>
        <DataGridTextColumn Foreground="Black" Width="140" Header="Address"  Binding="{Binding Address1, Mode=TwoWay}" IsReadOnly="True"/>
        <DataGridTextColumn Foreground="Black" Width="50" Header="Bulk   or Bag"  Binding="{Binding BulkorBag, Mode=TwoWay}" IsReadOnly="True"/>
        <DataGridTextColumn Foreground="Black" Width="80" Header="ProdCode" Binding="{Binding ProdCode, Mode=TwoWay}" IsReadOnly="True"/>
        <DataGridTextColumn Foreground="Black" Width="80" Header="MedCode" Binding="{Binding MedCode, Mode=TwoWay}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>
于 2014-06-18T15:39:45.197 回答