我正在尝试通过制作魔术卡应用程序来学习 MVVM。从概念上讲,我不知道如何将数据和命令从视图模型链接到视图中。我了解如何在视图模型中提供数据,但不了解如何从视图中访问它。
主要问题是 xaml 中有什么不正确,我在按钮上遇到异常,我假设与命令绑定有关,这也意味着数据可能也不起作用。
<Window x:Class="MagicDB.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MagicDB"
Title="MainWindow" Width="500" Height="500">
<Window.DataContext>
<local:MainWindowViewModel x:Name="viewModel" />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50*" />
<RowDefinition Height="450*" />
</Grid.RowDefinitions>
<DataGrid AutoGenerateColumns="False"
HorizontalAlignment="Left"
VerticalAlignment="Top"
IsSynchronizedWithCurrentItem="True" Width="auto" Height="auto" Grid.Row="1">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding CardID}" Width="25" ></DataGridTextColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="110"></DataGridTextColumn>
<DataGridTextColumn Header="Mana" Binding="{Binding Mana}" Width="30" ></DataGridTextColumn>
<DataGridTextColumn Header="Card Text" Binding="{Binding CardTXT}" Width="100*"></DataGridTextColumn>
<DataGridTextColumn Header="Flavor Text" Binding="{Binding FlavorTXT}" Width="100*"></DataGridTextColumn>
<!--DataGridCheckBoxColumn Header="Cost" Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" ></DataGridCheckBoxColumn-->
</DataGrid.Columns>
</DataGrid>
<Button Content="Initiliaze Database" Height="23" HorizontalAlignment="Left" Margin="55,16,0,0" Name="initdb" VerticalAlignment="Top" Width="75"
Command="Binding InitCardDB"/>
</Grid>
主要问题是按钮上引发了异常。我也不认为我正在获取网格的数据。
namespace MagicDB
{
class MainWindowViewModel : ObservableObject
{
private CardDB _cards;
private Command _InitCardDB;
public CardDB Cards
{
get { return _cards; }
set { _cards = value; OnPropertyChanged("Cards"); }
}
public MainWindowViewModel()
{
//var cards = GetCards();
//var cardViewModels = new List<CardViewModel>();
//cards.ForEach(c => cardViewModels.Add(new CardViewModel(c)));
_InitCardDB = new Command(InitDB, true);
Cards = new CardDB(); ;
}
public Command InitCardDB
{
get
{
if (_InitCardDB == null)
{
_InitCardDB = new Command(
param => InitDB()
);
}
return _InitCardDB;
}
}
private void InitDB()
{
_cards = new CardDB();
_cards.InitDB();
}
}
}
任何帮助都会很棒,尤其是我做错了什么以及我在概念上犯了错误的地方。我可能完全不正确地处理这个问题?在此先感谢您的时间。