c# - 我希望 wpf DataGrid 的其余部分中的数据是只读的,只有新行应该是可编辑的

标签 c# wpf mvvm datagrid

我已经设法让 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>

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

最佳答案

试试这个 MSDN blog

另外,试试下面的例子:

Xaml:

   <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; }
}

关于c# - 我希望 wpf DataGrid 的其余部分中的数据是只读的,只有新行应该是可编辑的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16251327/

相关文章:

c# - 如何使用 C# 从 Azure 删除 blob 不可变文件

c# - 在 datagridview 组合框中将查询结果显示为默认项

c# - 如何在文件中替换2个双引号

wpf - CollectionViewSource.GetDefaultView 不在 Silverlight 3 中!有什么解决办法吗?

wpf - 从 XAML 设置 ViewModel 属性值

c# - 如何在 asp.net c# 中通过下拉列表获取最近 3 年的数据?

c# - 如何告诉元素及其子元素忽略全局样式

wpf - 在哪里放置 MVVM CustomControl ViewModels/类 WPF

silverlight - 带有 ObservableCollections 的 ObservableCollection 无法正确呈现

WPF 设计问题(自定义控件或 mvvm)