MVVM模式。
你的XAML代码:
<DataGrid Name="myGrid" Grid.Row="1" SelectionMode="Single" AutoGenerateColumns="False" CanUserAddRows="True" ItemsSource="{Binding YourCollection}" IsReadOnly="True" Background="#FFB8C1CB">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding yourColumnItem}" />
</DataGrid.Columns>
</DataGrid>
ViewModel:
public ObservableCollection<YourType> YourCollection { get; private set; }
public DelegateCommand checkCommand { get; private set; }
public YourViewModel(){
checkCommand = new checkCommand(param => checkExecuted(param));
}
private void CheckExecuted(Object param)
{
YourType item = param as YourType;
YourCollection = new ObservableCollection<YourType>();
YourCollection = model.ReadInvoices();
DoStuff(item.yourColumnItem);
}
App.xaml.cs
private YourViewModel _ViewModel;
public App()
{
_ViewModel = new YourViewModel();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
_MainWindow = new MainWindow();
_MainWindow.DataContext = _ViewModel;
_MainWindow.Show();
}
你的DelegateCommand类:
using System;
using System.Windows.Input;
namespace yourSolution.ViewModel
{
public class DelegateCommand : ICommand
{
private readonly Action<Object> _Execute;
private readonly Func<Object, Boolean> _CanExecute;
public DelegateCommand(Action<Object> execute) : this(null, execute) { }
public DelegateCommand(Func<Object, Boolean> canExecute, Action<Object> execute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_Execute = execute;
_CanExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public Boolean CanExecute(Object parameter)
{
return _CanExecute == null ? true : _CanExecute(parameter);
}
public void Execute(Object parameter)
{
_Execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
DatabaseModel.cs:
public ObservableCollection<YourType> ReadInvoices()
{
Connect();
YourCollection.Clear();
MySqlCommand cmd = new MySqlCommand(write your query);
MySqlDataReader dr = cmd.ExecuteReader();
YourCollection.Clear();
YourType item = new YourType();
while (dr.Read()){
item.column = dr.GetInt32("columnName");
YourCollection.Add(item);
}
dr.Close();
Disconnect();
return YourCollection;
}
将您的命令绑定在 xaml 中的所选项上。这样它就会成为 CheckCommand 的参数:
Command="{Binding CheckCommand}" CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}"
我希望这个可以涵盖所有内容。当然,你需要EventHandlers来与App.xaml.cs通信,但我不知道你在处理单元格后想做什么。我只做过这三次,希望一切顺利。