C# Wpf DataGrid 添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16251327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wpf DataGrid Add new row
提问by Mandar Jogalekar
I have managed to get DataGridto show new row for adding new item.
Problem i face now is i want data in the rest of wpf DataGridto be read only and only new row should be editable.
我设法DataGrid显示新行以添加新项目。我现在面临的问题是我希望 wpf 其余部分的数据DataGrid是只读的,并且只有新行应该是可编辑的。
Currently this is how my DataGridlooks.
目前这就是我的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>
But since I have kept the columns read only, a new row also adds as read only which is what I don't want.
但是由于我将列保持为只读,因此新行也添加为只读,这是我不想要的。
采纳答案by Elyor
Try this MSDN blog
试试这个MSDN 博客
Also, try the following example:
另外,请尝试以下示例:
Xaml:
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:
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; }
}
回答by Kylo Ren
Just simply use this Styleof DataGridRow:
只需简单地使用这个Style的DataGridRow:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>

