Wpf DataGrid Add new row

前端 未结 2 759
一生所求
一生所求 2020-12-08 14:06

I have managed to get DataGrid to show new row for adding new item. Problem i face now is i want data in the rest of wpf DataGrid to be read only a

相关标签:
2条回答
  • 2020-12-08 14:55

    Try this MSDN blog

    Also, try the following example:

    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; }
    }
    
    0 讨论(0)
  • 2020-12-08 15:10

    Just simply use this Style of DataGridRow:

    <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
            </Style>
    </DataGrid.RowStyle>
    
    0 讨论(0)
提交回复
热议问题