(视图模型)返回空值的数据上下文

本文关键字:数据 上下文 空值 返回 视图 模型 | 更新日期: 2023-09-27 18:34:29

我有以下事件:

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; 设置当前视图模型以反映我的 UI 正在运行的信息。 不幸的是,它返回 null,我不确定为什么。

这显然突出了我对这个主题的理解差距,但不确定如何解决这个问题,我可以用手。知道我哪里出错了吗?

(视图模型)返回空值的数据上下文

您尚未将DataContext分配给任何地方ViewModel。假设您希望ViewModel是 MainWindow 的 ViewModel,我建议您在Initialize Component之前分配它,如下所示。由于它从未分配过,因此您将获得空值。

public MainWindow()
{
    ConnectFourViewModel ViewModel = new ConnectFourViewModel();
    . . .
    . . .
    DataContext = ViewModel ;
    InitializeComponent();
}