29

我已经设法DataGrid显示新行以添加新项目。我现在面临的问题是我希望 wpf 其余部分中的数据DataGrid是只读的,并且只有新行应该是可编辑的。

目前这就是我的DataGrid样子。

<DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" Grid.Row="2" ItemsSource="{Binding TestBinding}" >
    <DataGrid.Columns>        
        <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
        <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>               
    </DataGrid.Columns>
</DataGrid>

但是由于我将列保持为只读,因此新行也会添加为只读,这是我不想要的。

4

2 回答 2

41

试试这个MSDN 博客

另外,请尝试以下示例:

xml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}
于 2013-04-27T11:11:41.490 回答
18

只需简单地使用这个StyleDataGridRow

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>
于 2016-02-16T17:05:14.327 回答