要在 WPF 中使用 MVVMLight 来实现后台绑定一个集合给 ListView 并实现动态刷新,你需要按照以下步骤进行操作:

  1. 首先,确保已经在项目中安装了 MVVMLight 的 NuGet 包。

  2. 在 ViewModel 中创建一个 ObservableCollection 属性,用于存储要绑定给 ListView 的集合。例如:

private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
    get { return _items; }
    set { _items = value; RaisePropertyChanged('Items'); }
}
  1. 在 ViewModel 的构造函数中初始化 Items 集合,并添加一些初始数据。例如:
public MyViewModel()
{
    Items = new ObservableCollection<string>();
    Items.Add('Item 1');
    Items.Add('Item 2');
    Items.Add('Item 3');
}
  1. 在 XAML 中,使用 MVVMLight 的 ViewModelLocator 来绑定 ViewModel 和 View。例如:
<Window x:Class="YourNamespace.MainWindow"
        xmlns:vm="clr-namespace:YourNamespace.ViewModels"
        xmlns:views="clr-namespace:YourNamespace.Views"
        xmlns:local="clr-namespace:YourNamespace"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vm:MyViewModel/>
    </Window.DataContext>
    <Grid>
        <ListView ItemsSource="{Binding Items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>
  1. 运行程序,你将会看到初始的 Items 集合中的数据在 ListView 中显示出来。

  2. 如果需要动态刷新 ListView 中的数据,只需在 ViewModel 中修改 Items 集合即可。例如,在 ViewModel 中添加一个方法来添加新的数据项:

public void AddItem(string item)
{
    Items.Add(item);
}

然后在需要的地方调用该方法即可实现动态刷新。例如,在 ViewModel 的构造函数或者某个命令中调用该方法:

public MyViewModel()
{
    Items = new ObservableCollection<string>();
    Items.Add('Item 1');
    Items.Add('Item 2');
    Items.Add('Item 3');
    AddItem('New Item');
}

这样,当程序运行时,ListView 中将会显示出新添加的数据项。


原文地址: https://www.cveoy.top/t/topic/qrkO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录