1

我是 WPF 的新手。我曾经在Winforms工作过。

在 Winforms 中,当我想要一个单元格值时,我有允许我更改的 DataGridView。

只需使用:

dataGridView[columnIndex, rowIndex].Value = "New Value";

有用。

如何使用 WPF 中的 DataGrid 完成此操作?我一直在寻找完整的堆栈,并且可以找到一种简单的方法来做到这一点。

谢谢

4

1 回答 1

1

好的,最简单的处理方法DataGrid是绑定到ItemSource.

下面的示例显示了如何绑定您的列表以及如何更改更新 DataGrid。

public partial class MainWindow : Window
{
    private ObservableCollection<ConnectionItem> _connectionitems = new ObservableCollection<ConnectionItem>();

    public MainWindow()
    {
        InitializeComponent();
        ConnectionItems.Add(new ConnectionItem { Name = "Item1", Ping = "150ms" });
        ConnectionItems.Add(new ConnectionItem { Name = "Item2", Ping = "122ms" });
    }

    public ObservableCollection<ConnectionItem> ConnectionItems
    {
        get { return _connectionitems; }
        set { _connectionitems = value; }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        // to change a value jus find the item you want in the list and change it
        // because your ConnectionItem class implements INotifyPropertyChanged
        // ite will automaticly update the dataGrid

        // Example
        ConnectionItems[0].Ping = "new ping :)";
    }
}

public class ConnectionItem : INotifyPropertyChanged
{
    private string _name;
    private string _ping;

    public string Name
    {
        get { return _name; }
        set { _name = value; NotifyPropertyChanged("Name"); }
    }

    public string Ping
    {
        get { return _ping; }
        set { _ping = value; NotifyPropertyChanged("Ping"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    /// <summary>
    /// Notifies the property changed.
    /// </summary>
    /// <param name="property">The info.</param>
    public void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

xml:

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication4"
        xmlns:properties="clr-namespace:WpfApplication4.Properties"
        Title="MainWindow" Height="300" Width="400" Name="UI" >
    <Grid>
        <DataGrid Name="dataGridView" ItemsSource="{Binding ElementName=UI,Path=ConnectionItems}" Margin="0,0,0,40" />
        <Button Content="Change" Height="23" HorizontalAlignment="Left" Margin="5,0,0,12" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click" />
    </Grid>
</Window>

我添加了一个按钮来显示当您更改列表中的某些内容时数据如何更新,ConnectionItem 类是您存储数据网格所有信息的地方。

希望这可以帮助

于 2012-12-17T01:29:24.260 回答