我想在按钮点击上添加数据到数据网格。假设一个带有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中是否可行?我已经在使用jquery和后端方法的Web应用程序中完成了这项工作。无论如何,我希望在WPF中也很容易。我搜索过网,但是所有的例子似乎都很复杂,数据绑定,我不想做数据绑定,并且想用上面我试图解释的简单方法,希望它清楚。
答案 0 :(得分:0)
我将同意这两个评论者,数据绑定是这样做的方式,我知道它起初看起来很复杂但是一旦你得到一个很好的转换器和命令库,它可以一次又一次地重复使用,上面的简单数据绑定示例如下所示。
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背后的代码,这里我创建了两个我们可以绑定的属性,一个是包含将显示为行的数组的项目,另一个是可以调用以添加另一行的命令
此处的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&amp; 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);
}
}
答案 1 :(得分:0)
为了展示使用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项目中,并按原样使用它。
这是我的主窗口的viewmodel: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();
}
}
如您所见,我有一个InventoryItemViewModels的ObservableCollection。这是我从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();
}
}