【发布时间】:2020-09-15 21:12:23
【问题描述】:
我正在尝试将位于我的 ViewModel 类中的 ObservableCollection 绑定到使用 GridView 显示行的 ListView,但我无法在列表中显示我的数据。
出于测试目的,我放置了一个 TextBlock,并且可以使用 Binding 成功显示数据(但是只有在我先在后面的代码中执行 DataContext = ViewModel 时,在 XAML 中执行 ViewModel.MyData 才行)
我注意到无论ItemsSource 绑定到什么,列表中总会显示随机数量的空元素,我可以说,因为当我将鼠标悬停在 ListView 上时,行会突出显示。这个数字与我收藏的容量不匹配。
如果在后面的代码中我手动将ItemsSource 设置为我要显示的集合,则会显示正确数量的元素,但仍然没有显示数据。
XAML
<Page x:Class="GestionStockWPF.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GestionStockWPF"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="MainPage"
ShowsNavigationUI="False">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="13*"/>
<RowDefinition Height="77*"/>
</Grid.RowDefinitions>
<!-- The Binding here seems to do nothing, there isn't the correct amount of rows in the app -->
<ListView x:Name="listView"
HorizontalAlignment="Stretch"
Grid.Row="1" Margin="30, 0, 30, 30"
ItemsSource="{Binding Source=Tests}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=A}"
Header="Asset Number" Width="200"/>
</GridView>
</ListView.View>
</ListView>
<!-- This textblock is just here for testing purposes, it successfully shows "A" -->
<TextBlock x:Name="textBlock" Text="{Binding Path=Tests[0].A}"
HorizontalAlignment="Left" Margin="252,28,0,0" TextWrapping="Wrap"
VerticalAlignment="Top"/>
</Grid>
</Page>
文件背后的代码
using System.Windows;
using System.Windows.Controls;
namespace GestionStockWPF
{
public partial class MainPage : Page
{
public MainPageViewModel ViewModel;
public MainPage()
{
InitializeComponent();
ViewModel = new MainPageViewModel();
// If I do DataContext = this;
// and then set the binding of the TextBlock to "ViewModel.Tests[0].A" nothing is shown
DataContext = ViewModel;
// If I don't do that the listview does not contain the correct number of rows
listView.ItemsSource = ViewModel.tests;
}
}
}
ViewModel 和测试类
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace GestionStockWPF
{
// Not sure if I have to implement INotifyPropertyChanged but my real class does it
public class Test : INotifyPropertyChanged
{
public string A { get { return "A"; } }
public string B { get { return "B"; } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public class MainPageViewModel
{
public ObservableCollection<Test> Tests { get; set; }
public MainPageViewModel()
{
tests = new ObservableCollection<Test>();
for (int i = 0; i < 50; ++i)
{
Tests.Add(new Test());
}
}
}
}
【问题讨论】:
-
DataContext = this不起作用,因为绑定需要属性,而ViewModel是一个字段。
标签: c# wpf mvvm data-binding