我在绑定到列表视图时遇到问题。
视图模型:
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
}
private ObservableCollection<Player> players;
public ObservableCollection<Player> Players
{
get { return players; }
set
{
players = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Players"));
}
}
private List<string> playerNames = new List<string>();
public List<string> PlayerNames
{
get { return playerNames; }
set
{
playerNames = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("PlayerNames"));
}
}
private GameType selectedGame;
public GameType SelectedGame
{
get { return selectedGame; }
set
{
selectedGame = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedGame"));
}
}
private string gameName;
public string GameName
{
get { return gameName; }
set
{
gameName = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("GameName"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
玩家:
public class Player : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set { name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name")); }
}
private string currentScore = "0";
public string CurrentScore
{
get { return currentScore; }
set { currentScore = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentScore")); }
}
private string gamesWon = "0";
public string GamesWon
{
get { return gamesWon; }
set { gamesWon = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("GamesWon")); }
}
//public override string ToString()
//{
// return Name;
//}
}
列表视图:
<ListView x:Name="listviewPlayers" HorizontalOptions="End" ItemsSource="{Binding Players}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Players.Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
更新视图模型:
public void InitGame(Game game)
{
//initialize points and setup first player
viewModel.Players = game.Players;
viewModel.SelectedGame = game.SelectedGame;
viewModel.GameName = game.SelectedGame.Name;
contentMain.BindingContext = viewModel;
}
上述 ListView 绑定不起作用 - 出现错误:在类型“ObservableCollection`1”中找不到属性“Name”。但是,如果我删除 ItemTemplate 并将列表视图的项目源绑定到 {Binding Players[0].Name},列表视图将显示列表玩家中的每个名称。 我看不出我做错了什么。希望在这里得到一些帮助。
谢谢,迈克
这样做
<Label Text="{Binding Name}" />
每行的 BindingContext
是
ItemsSource
的匹配元素,因此在您的情况下,它是单独的
Player
实例