I've got the following event:
private void PlaceToken(object sender, RoutedEventArgs e)
{
ConnectFourViewModel currentViewModel = (ConnectFourViewModel)DataContext;
Button button = (Button)sender;
int currentColumn = Convert.ToInt32(button.Content);
int currentPlayer = currentViewModel.Board.CurrentPlayer;
currentViewModel.Board.PlaceToken(currentColumn, currentPlayer);
}
在以下设置完成后:
public MainWindow()
{
var window = new Window();
var grid = new Grid {};
ConnectFourViewModel ViewModel = new ConnectFourViewModel();
//Set up rows and cols
for(int i = 1; i<=7; i++)
{
var col = new ColumnDefinition();
grid.ColumnDefinitions.Add(col);
}
for (int i = 1; i <= 7; i++)
{
var row = new RowDefinition();
grid.RowDefinitions.Add(row);
}
//Set up tiles
foreach (var item in ViewModel.Board.AllTiles)
{
int index = ViewModel.Board.AllTiles.IndexOf(item);
string name =
"Col" +
Convert.ToString(item.Column) +
"_Row" +
Convert.ToString(item.Row);
Label currentTile = new Label{ Name = name};
Grid.SetRow(currentTile, item.Row - 1);
Grid.SetColumn(currentTile, item.Column -1);
//Bind
var binding = new Binding();
binding.Source = ViewModel.Board.AllTiles[index];
binding.Path = new PropertyPath("Contents");
currentTile.SetBinding(ContentProperty, binding);
//Add
grid.Children.Add(currentTile);
}
//Set up Buttons
for (int i = 1; i <= 7; i++)
{
Button currentButton = new Button { };
//binding
var binding = new Binding();
binding.Source = ViewModel.CurrentColumn;
currentButton.SetBinding(ContentProperty, binding);
//Set Column names, this has to be after the binding has been set.
currentButton.Content = i;
//events
currentButton.Click += new RoutedEventHandler(PlaceToken);
//add
Grid.SetColumn(currentButton, i - 1);
Grid.SetRow(currentButton, 7);
grid.Children.Add(currentButton);
}
window.Content = grid;
window.DataContext = ViewModel;
window.Show();
InitializeComponent();
}
我希望这一行代码:ConnectFourViewModel currentViewModel = (ConnectFourViewModel)DataContext; 可以设置currentViewModel以反映我的UI正在运行的信息。不幸的是,它返回null,我不知道为什么。
这显然凸显了我对这个主题的理解上存在的差距,但我不确定该如何解决,所以需要帮忙。有任何想法吗?我哪里出错了吗?