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

时间:2013-02-11 16:04:05

标签: wpf datagrid

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

<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}" />

1 个答案:

答案 0 :(得分:12)

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

  1. 设置AutoGenerateColumns =&#34; False&#34;在DataGrid上并设置IsReadOnly =&#34; True&#34;对于除了要编辑的列之外的所有列,您将设置IsReadOnly =&#34; False&#34;。
  2. 的AutoGenerateColumns =&#34;真&#34; (这是默认设置,因此您可以从XAML中删除该属性)并在ViewModel中为所有属性设置私有设置,除了您想要编辑的列。
  3. 以下是选项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>