【发布时间】:2016-11-18 20:56:50
【问题描述】:
在 UWP 应用中,我试图将 ListBox 注入内容控件。正如您将在我提交的代码中看到的那样,ListBox 的 ItemsSource 绑定未注册到 PropertyChanged 事件,因此当我尝试将 ItemsSource 更改为新集合时,它不会在列表中直观地反映出来。我知道引用是正确的,因为如果我在设置绑定之前先创建新集合,屏幕会显示列表。我需要做什么才能使以下代码正常工作?
<Page
x:Class="App2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ContentControl Content="{x:Bind MyRootControl, Mode=OneWay}"/>
</Grid>
</Page>
和
using System.Collections.ObjectModel;
using System.ComponentModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace App2
{
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public MainPage()
{
this.InitializeComponent();
BindingOperations.SetBinding(MyRootControl, ItemsControl.ItemsSourceProperty, new Binding() { Source = myData, Mode = BindingMode.OneWay });
myData = new ObservableCollection<string>(new[] { "hello", "world" });
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(myData)));
}
public ObservableCollection<string> myData { get; set; } = new ObservableCollection<string>();
public ListBox MyRootControl { get; set; } = new ListBox();
public event PropertyChangedEventHandler PropertyChanged;
}
}
【问题讨论】:
-
在派生自 DependencyObject 的类中实现 INotifyPropertyChanged 没有意义。相反,
myData应该是一个依赖属性。目前,myData 甚至不是属性,而只是一个字段,因此不支持数据绑定。除此之外,目前还不清楚你想用它做什么。 -
@Clemens。抱歉,在尝试将问题浓缩为这个简单的代码示例时,出现了一些严重的疏忽。我已在原始问题中更正了这些问题,该问题仍然存在。我试图理解为什么更改 ListBox 集合不会反映在内容控件中,因为它是编写的。转换为依赖属性不会回答这个问题。
-
在这里实现 INotifyPropertyChanged 仍然没有意义。除此之外,使用属性名称“myData”触发 PropertyChanged 事件在这里没有任何效果,因为您的绑定设置不正确。
Binding.Source应该是拥有该属性的对象 (this),Binding.Path应该设置为new PropertyPath("myData")。 -
@Clemens... 做到了!痛苦的显而易见,因为它现在摆在我面前,哈哈。你能把 BindingOperations.SetBinding(MyRootControl, ItemsControl.ItemsSourceProperty, new Binding() { Source = this, Path= new PropertyPath("myData"), Mode = BindingMode.OneWay });作为您的答案,我会将其标记为已回答?
-
为了进一步证明这个例子的合理性,原始问题使用了一个不是从 DependencyObject 派生的视图模型,并使用 INotifyPropertyChanged 来促进绑定,因此这个 Occam 的
标签: c# xaml uwp win-universal-app xbind