具有Window
且包含DataGrid
的WPF应用程序,试图实现MVVM体系结构。只有一个Model类:
public class Book
{
public int id {get; set;}
public string title {get; set;}
public string isbn {get; set;}
}
这是ViewModel:
class BookViewModel
{
public ObservableCollection<Book> Books;
public BookViewModel()
{
Books = new ObservableCollection<Book>();
// TODO: execute LoadData comand
}
}
用于视图标记的XAML代码的一部分,它由一个Window组成:
<Window.CommandBindings>
<CommandBinding Command="self:CustomCommands.LoadData" CanExecute="LoadDataCommand_CanExecute" Executed="LoadDataCommand_Executed"/>
</Window.CommandBindings>
<DataGrid Name="BooksDataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Width="200" Binding="{Binding title}"/>
<DataGridTextColumn Header="isbn" Width="200" Binding="{Binding isbn}"/>
</DataGrid.Columns>
</DataGrid>
上方视图的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// TODO: execute LoadData command
}
private void LoadDataCommand_CanExecute(object sender, CanExecuteRoutedEventArgs args)
{
args.CanExecute = true;
}
private void LoadDataCommand_Executed(object sender, ExecutedRoutedEventArgs args)
{
// TODO: ask the model for the data
}
}
public static class CustomCommands
{
public static readonly RoutedUICommand LoadData = new RoutedUICommand
(
"LoadData",
"LoadData",
typeof(CustomCommands),
new InputGestureCollection()
{
// allow Ctrl+L to perform this command
new KeyGesture(Key.L, ModifierKeys.Control)
}
);
}
App.xaml的代码背后:
public partial class App : Application
{
[STAThread()]
public static void Main()
{
App app = new App();
app.InitializeComponent();
app.Run();
}
// bind application and show main window on startup
// data context is default source of bindings
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
View.MainWindow mainWin = new View.MainWindow();
ViewModel.BookViewModel bookViewModel = new ViewModel.BookViewModel();
mainWin.DataContext = bookViewModel;
mainWin.Show();
}
}
我正在从WinForms过渡到WPF,并发现WPF的某些方面令人困惑。试图实现的目标和面临的问题如下:
LoadData
命令应清除GridView
,然后从数据库再次填充。数据库连接已经实现。到目前为止,我还看不到如何使数据绑定起作用。LoadData
命令应同时通过菜单和按钮执行(已实现)。LoadData
命令应在应用程序启动时执行。因此,DataGrid
启动时将被填充。除了初始化组件和设置数据上下文之外,窗口的代码不应包含太多代码。
public MainWindow()
{
IntializeComponent();
DataContext = new BookViewModel();
}
并且您的loadData命令将在BookViewModel中实现
private ICommand _loadDataCommand;
public Icommand LoadDataCommand => _loadDataCommand ?? _loadDataCommand = new RelayCommand((obj) => LoadDataCommand = LoadData(), can_execute condition);
public void LoadData()
{
}
为了使上面的代码起作用,您还需要实现RelayCommand.cs,有关此代码,请参见:Full implementation of Relay Command - can it be applied to all cases?。此外,RelayCommand实现还在线提供了许多其他有用的答案和资源。