为什么这种绑定不起作用?
<Window x:Class="S3PackageInstaller.MainWindow" x:Name="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s3u="clr-namespace:S3PackageInstaller"
Icon="App.ico" Title="Sims 3 Package Installer" Height="480" Width="740">
<DockPanel LastChildFill="True">
<DockPanel DockPanel.Dock="Left" Width="200" VerticalAlignment="Stretch" LastChildFill="True"
Margin="20,20,0,20">
<!-- this is the binding that isn't working -->
<ListView Width="200" ItemsSource="{Binding ElementName=Window1, Path=InstalledPackages}">
<ListView.View>
<GridView>
<GridViewColumn Header="Installed Packages" DisplayMemberBinding="{Binding Filename}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<!-- snip -->
</Window>
背后的相关代码:
public partial class MainWindow : Window
{
public ObservableCollection<object> InstalledPackages { get; private set; }
public MainWindow()
{
InitializeComponent();
InstalledPackages = new ObservableCollection<object>();
LoadInstalledPackages();
}
private void LoadInstalledPackages()
{
var installPath = Settings.Default.TargetDirectory;
var packages = System.IO.Directory.GetFiles(installPath, "*.package");
InstalledPackages.Clear();
foreach (string filename in packages)
InstalledPackages.Add(new { Filename = filename });
}
// snip...
}
当我运行程序时,ListView为空。调试时,我已验证该集合包含LoadInstalledPackages运行后的项目。
答案 0 :(得分:1)
我认为问题在于,虽然您的集合属性是ObservableCollection
,因此会通知集合更改,属性本身在您首次分配时不会引发更改通知。按如下方式创建窗口时:
public MainWindow()
{
InitializeComponent();
InstalledPackages = new ObservableCollection<object>();
LoadInstalledPackages();
}
调用InitializeComponent
时,会创建UI并构造绑定。此时InstalledPackages
为空。在下一行中,您可以创建集合,但由于InstalledPackages
未引发PropertyChanged
事件,因此您的绑定不会更新。
在调用INotifyPropertyChanged
之前,实施ObservableCollection
或将InitializeComponent
分配给此媒体资源。