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

WPF中ListView无法显示ViewModel枚举数据的问题求助

WPF ListView无法显示枚举数据问题排查

问题描述

我正在制作一个WPF页面示例,尝试通过ViewModel展示枚举数据,但ListView始终无法正常显示数据。


相关代码

GameParticipants类与IGameParticipants接口

public class GameParticipants: IGameParticipants
{
    public int Id{ get; set; }
    public List<string> Name { get; set; }
    public Dictionary<int,string> GameWinner { get; set; }
    public DateTime WinningDate { get; set; }
}

public interface IGameParticipants
{
    List<string> Name { get; set; }
    Dictionary<int, string> GameWinner { get; set; }
    DateTime WinningDate { get; set; }
}

ParticipantsViewModel.cs

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }
}

public class ParticipantsViewModel : ViewModelBase
{
    public string RemoveUnderscore(string text)
    {
        return text.Replace("_", " ");
    }
    public ParticipantsViewModel()
    {
        Participants = new GamesParticipants()
        {
            Name = new List<string>()
            {
                Handball.ToString(),
                Football.ToString(),
                Cricket.ToString(),
                Badminton.ToString(),
                Tennis.ToString(),
                TableTenis.ToString(),
                Rugby.ToString(),
                Boxing.ToString(),

            }
        };
    }

    private GamesParticipants _participants;
    public GamesParticipants Participants
    {
        get { return _participants; }
        set
        {
            _participants = value;
            RaisePropertyChanged("Participants");
        }
    }
}

MainWindow.xaml

<Window x:Class="Games.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Games"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Grid.DataContext>
        <local:ParticipantsViewModel/>
    </Grid.DataContext>
    
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <ListView ItemsSource="{Binding Path=Participants}" x:Name="lstParticipants" Grid.Row="1" Grid.Column="1" 
      VerticalContentAlignment="Top" ScrollViewer.CanContentScroll="True" d:ItemsSource="{d:SampleData ItemCount=13}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Viewbox>
                    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Horizontal">
                        <TextBlock Grid.Row="0" Text="{Binding Name}" TextWrapping="Wrap" FontWeight="Bold" FontSize="40" Foreground="Black" />
                    </StackPanel>
                </Viewbox>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    
    <Button x:Name="btnRandom" Grid.Row="2" Content="First Game" FontSize="45" Foreground="Green" Cursor="Hand"
            
            Grid.Column="1" VerticalAlignment="Center" Click="btnRandom_Click"></Button>

</Grid>

界面效果

MainWindow界面


问题原因

  1. 绑定源类型不匹配:ListView的ItemsSource绑定到了单个GamesParticipants对象(类名存在笔误,定义的是GameParticipants),但ListView需要绑定集合类型(如List<T>、ObservableCollection<T>)才能展示多条数据。
  2. 数据层级错误:你想展示的是Name列表中的枚举值,但当前绑定的是整个对象,ItemTemplate里的{Binding Name}会输出List<string>的默认ToString结果,而非单个元素内容。
  3. 类名笔误:ViewModel中实例化的GamesParticipants与定义的GameParticipants类名不一致,会导致编译错误。

修复步骤

1. 修正ViewModel数据结构

直接暴露要展示的集合作为绑定源,推荐使用ObservableCollection<T>(支持自动更新UI):

public class ParticipantsViewModel : ViewModelBase
{
    public string RemoveUnderscore(string text)
    {
        return text.Replace("_", " ");
    }
    
    public ParticipantsViewModel()
    {
        // 直接初始化要展示的游戏名称集合
        GameNames = new ObservableCollection<string>()
        {
            "Handball",
            "Football",
            "Cricket",
            "Badminton",
            "Tennis",
            "TableTenis",
            "Rugby",
            "Boxing"
        };
    }

    private ObservableCollection<string> _gameNames;
    public ObservableCollection<string> GameNames
    {
        get { return _gameNames; }
        set
        {
            _gameNames = value;
            RaisePropertyChanged(nameof(GameNames));
        }
    }
}

2. 调整ListView绑定

修改XAML中ListView的ItemsSource为新的集合属性,并调整ItemTemplate绑定到当前集合元素:

<ListView ItemsSource="{Binding GameNames}" x:Name="lstParticipants" Grid.Row="1" Grid.Column="1" 
          VerticalContentAlignment="Top" ScrollViewer.CanContentScroll="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Viewbox>
                <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
                    <TextBlock Text="{Binding}" TextWrapping="Wrap" FontWeight="Bold" FontSize="40" Foreground="Black" />
                </StackPanel>
            </Viewbox>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

3. 统一类名(若存在笔误)

将ViewModel中的GamesParticipants改为GameParticipants,确保与定义的类名一致:

private GameParticipants _participants;
public GameParticipants Participants
{
    get { return _participants; }
    set
    {
        _participants = value;
        RaisePropertyChanged(nameof(Participants));
    }
}

额外优化:直接绑定枚举

如果Handball等是枚举值,可直接绑定枚举更规范:
首先定义枚举:

public enum GameType
{
    Handball,
    Football,
    Cricket,
    Badminton,
    Tennis,
    TableTenis,
    Rugby,
    Boxing
}

然后在ViewModel中获取枚举值:

GameNames = new ObservableCollection<string>(Enum.GetNames(typeof(GameType)).Select(RemoveUnderscore));

内容的提问来源于stack exchange,提问作者Ashish-BeJovial

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:28:14