You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中Pokemon Abilities列表显示异常问题求助

解决.NET MAUI中Pokemon能力列表显示问题

问题根源

直接将List<Ability>绑定到Label.Text时,MAUI会调用集合的ToString()方法,因此显示类型全称;同时CollectionView的模板引用、数据源绑定存在错误,导致能力列表无法正确渲染。

具体修复步骤

1. 移除错误的Label绑定

删除视图中直接绑定SelectedPokemon.Abilities的Label,集合无法通过单个Label展示:

<!-- 删除该行错误代码 -->
<Label 
    Text="{Binding SelectedPokemon.Abilities}"
    VerticalOptions="Center" 
    HorizontalOptions="Center" />

2. 修正CollectionView的模板与数据源绑定

你的数据模板Key是Abilities,但CollectionView中误用了AbilitiesTemplate,同时直接绑定选中Pokemon的能力列表即可:

<CollectionView
    x:Name="PokemonsAbilities"
    ItemTemplate="{StaticResource Abilities}" <!-- 修正模板引用 -->
    ItemsSource="{Binding MonSelectedPokemon.Abilities}"> <!-- 绑定选中Pokemon的能力集合 -->
</CollectionView>

3. 确保选中属性支持通知

ViewModel中的MonSelectedPokemon必须实现INotifyPropertyChanged,否则切换选中Pokemon时,能力列表不会同步更新:

public class PokemonViewModel : INotifyPropertyChanged
{
    private Pokemon _monSelectedPokemon;
    public Pokemon MonSelectedPokemon
    {
        get => _monSelectedPokemon;
        set
        {
            _monSelectedPokemon = value;
            OnPropertyChanged();
        }
    }

    // 实现INotifyPropertyChanged接口
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // 其他现有代码...
}

4. 优化集合类型(可选)

将Pokemon类中的List<Ability>改为ObservableCollection<Ability>,这样能力列表增删时界面会自动刷新:

public class Pokemon
{
    // 其他属性...
    public ObservableCollection<Ability> Abilities { get; set; } = new ObservableCollection<Ability>();
}

同步修改数据初始化代码:

Abilities = new ObservableCollection<Ability>()
{
    new Ability { Name = "Thunderbolt", NbPower = 120 },
    new Ability { Name = "Spark Ball GX", NbPower = 200 }
}

5. 调整能力模板布局(可选)

当前模板中两个Label会重叠,优化布局让名称和威力横向排列:

<DataTemplate x:Key="Abilities">
    <Grid ColumnDefinitions="*,Auto">
        <Label Text="{Binding Name}" Margin="5"/>
        <Label Text="{Binding NbPower}" Grid.Column="1" Margin="5"/>
    </Grid>
</DataTemplate>

内容的提问来源于stack exchange,提问作者Eloi Jahan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:55:22