[英]add and retrieve data from datagrid, WPF
我想将按钮单击上的数据添加到数据网格。 假设一个数据网格具有3个标头,即ITEM,QUANTITY,PRICE。 现在,当用户第一次单击时,我将像这样在第一行中获取数据。
1 1 1
然后在第二次点击,总数据将是
1 1 1
2 2 2
等等
1 1 1
2 2 2
3 3 3
4 4 4
. . .
. . .
. . .
. . .
n n n
当我单击一个对数组说的按钮时,我应该在arraylist中获取datagrid数据。 在WPF中这可能吗? 我已经在Web应用程序中使用jquery和backend方法做到了这一点。 无论如何,我希望这在WPF中也很容易。 我已经在网上搜索过,但是所有示例似乎都与数据绑定很复杂,我不想进行数据绑定,并且希望采用我尝试在上面解释的简单方法,希望它清晰易懂。
我将同意这两个注释器,数据绑定是实现此目的的方式,我知道起初它看起来很复杂,但是一旦您获得了不错的转换器和命令库,就可以一次又一次地重用它。上面的数据绑定示例如下所示。
XAML,创建一个新项目,并在主窗口中粘贴此代码,它所做的只是添加一个具有3列的数据网格和一个将添加新行的按钮。 请注意,此窗口的数据上下文设置为自身,这意味着MainWindow类的属性默认情况下将使用{Binding}公开。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="432,289,0,0" VerticalAlignment="Top" Width="75" Command="{Binding AddCommand}"/>
<DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="274" Width="497" AutoGenerateColumns="False" ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Field1}"/>
<DataGridTextColumn Binding="{Binding Field2}"/>
<DataGridTextColumn Binding="{Binding Field3}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
现在是MainWindow的代码,在这里我创建了两个可以绑定的属性,一个是Items,其中包含将作为行显示的数组,另一个是可以调用以添加另一行的命令。
这里的ObservableCollection具有一些方法,它们可以告诉绑定引擎何时更改行,因此您不必费心更新网格。
public partial class MainWindow : Window
{
public ObservableCollection<Item> Items
{
get { return (ObservableCollection<Item>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<Item>), typeof(MainWindow), new PropertyMetadata(null));
public SimpleCommand AddCommand
{
get { return (SimpleCommand)GetValue(AddCommandProperty); }
set { SetValue(AddCommandProperty, value); }
}
public static readonly DependencyProperty AddCommandProperty = DependencyProperty.Register("AddCommand", typeof(SimpleCommand), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<Item>();
AddCommand = new SimpleCommand(para =>
{
string nextNumber = Items.Count.ToString();
Items.Add(new Item() { Field1 = nextNumber, Field2 = nextNumber, Field3 = nextNumber });
});
}
}
Item类,这只是一个非常简单的类,具有3个与您的数据网格相匹配的属性,field1、2和3这里的依赖项属性还意味着您不必在数据更改时就麻烦自己更新网格。
public class Item : DependencyObject
{
public string Field1
{
get { return (string)GetValue(Field1Property); }
set { SetValue(Field1Property, value); }
}
public static readonly DependencyProperty Field1Property = DependencyProperty.Register("Field1", typeof(string), typeof(Item), new PropertyMetadata(null));
public string Field2
{
get { return (string)GetValue(Field2Property); }
set { SetValue(Field2Property, value); }
}
public static readonly DependencyProperty Field2Property = DependencyProperty.Register("Field2", typeof(string), typeof(Item), new PropertyMetadata(null));
public string Field3
{
get { return (string)GetValue(Field3Property); }
set { SetValue(Field3Property, value); }
}
public static readonly DependencyProperty Field3Property = DependencyProperty.Register("Field3", typeof(string), typeof(Item), new PropertyMetadata(null));
}
最后是命令类,它可以在所有项目中反复使用,以将某些内容链接到后面的代码。
public class SimpleCommand : DependencyObject, ICommand
{
readonly Action<object> _execute;
readonly Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged;
public SimpleCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_canExecute = canExecute == null ? parmeter => { return true; } : canExecute;
_execute = execute;
}
public virtual void Execute(object parameter)
{
_execute(parameter);
}
public virtual bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
}
为了展示使用DataBinding实现这一目标有多么容易,我迅速打开了这个小应用程序。 这花了我大约10分钟的时间,但是经验丰富的Resharper和其他工具的程序员可以在几分钟之内解决这个问题。
这是我的InventoryItemViewModel.cs
public class InventoryItemViewModel : ViewModelBase
{
private int _itemid;
public int ItemId
{
get { return _itemid; }
set { _itemid = value; this.OnPropertyChanged("ItemId"); }
}
private int _qty;
public int Qty
{
get { return _qty; }
set { _qty = value; this.OnPropertyChanged("Qty"); }
}
private int _price;
public int Price
{
get { return _price; }
set { _price = value; this.OnPropertyChanged("Price"); }
}
}
如您所见,这里没有太多,只有3个属性。 启用简单的UI更新的魔力是因为我实现了ViewModelBase。
这是ViewModelBase.cs
/// <summary>
/// Abstract base to consolidate common functionality of all ViewModels
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, e);
}
}
}
您几乎可以将该类复制到所有WPF项目中,并按原样使用。
这是我的主窗口的视图模型:MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
this.InventoryCollection = new ObservableCollection<InventoryItemViewModel>();
this.AddItemCommand = new DelegateCommand((o) => this.AddItem());
this.GetItemListCommand = new DelegateCommand((o) => this.GetInventoryItemList());
}
public ICommand AddItemCommand { get; private set; }
public ICommand GetItemListCommand { get; private set; }
public ObservableCollection<InventoryItemViewModel> InventoryCollection { get; private set; }
private void AddItem()
{
// get maxid in collection
var maxid = InventoryCollection.Count;
// if collection is not empty get the max id (which is the same as count in this case but whatever)
if (maxid > 0) maxid = InventoryCollection.Max(x => x.ItemId);
InventoryCollection.Add(new InventoryItemViewModel
{
ItemId = ++maxid,
Price = maxid,
Qty = maxid
});
}
private List<InventoryItemViewModel> GetInventoryItemList()
{
return this.InventoryCollection.ToList();
}
}
如您所见,我有一个ObventableCollection的InventoryItemViewModels。 这是我从UI绑定到的集合。 必须使用ObservableCollection而不是List或数组。 为了使按钮正常工作,我定义了ICommand属性,然后将这些属性绑定到UI中的按钮。 我使用DelegateCommand类将操作重定向到各自的私有方法。
这是DelegateCommand.cs,这是另一个类,您可以仅将其包含在WPF项目中并信任它可以正常工作。
public class DelegateCommand : ICommand
{
/// <summary>
/// Action to be performed when this command is executed
/// </summary>
private Action<object> executionAction;
/// <summary>
/// Predicate to determine if the command is valid for execution
/// </summary>
private Predicate<object> canExecutePredicate;
/// <summary>
/// Initializes a new instance of the DelegateCommand class.
/// The command will always be valid for execution.
/// </summary>
/// <param name="execute">The delegate to call on execution</param>
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Initializes a new instance of the DelegateCommand class.
/// </summary>
/// <param name="execute">The delegate to call on execution</param>
/// <param name="canExecute">The predicate to determine if command is valid for execution</param>
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.executionAction = execute;
this.canExecutePredicate = canExecute;
}
/// <summary>
/// Raised when CanExecute is changed
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Executes the delegate backing this DelegateCommand
/// </summary>
/// <param name="parameter">parameter to pass to predicate</param>
/// <returns>True if command is valid for execution</returns>
public bool CanExecute(object parameter)
{
return this.canExecutePredicate == null ? true : this.canExecutePredicate(parameter);
}
/// <summary>
/// Executes the delegate backing this DelegateCommand
/// </summary>
/// <param name="parameter">parameter to pass to delegate</param>
/// <exception cref="InvalidOperationException">Thrown if CanExecute returns false</exception>
public void Execute(object parameter)
{
if (!this.CanExecute(parameter))
{
throw new InvalidOperationException("The command is not valid for execution, check the CanExecute method before attempting to execute.");
}
this.executionAction(parameter);
}
我的MainWindow.xaml上的UI代码如下所示:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctlDefs="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
</Window.Resources>
<StackPanel>
<Button Command="{Binding Path=GetItemListCommand}" Content="Get Item List" />
<Button Command="{Binding Path=AddItemCommand}" Content="Add Item" />
<DataGrid ItemsSource="{Binding Path=InventoryCollection}" />
</StackPanel>
为了将它们粘合在一起,我重写了App.xaml.cs OnStartUp方法。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var mainvm = new MainWindowViewModel();
var window = new MainWindow
{
DataContext = mainvm
};
window.Show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.