在UWP应用程序中,我正在尝试将ListBox注入Content Control。正如您将从我提交的代码中看到的那样,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;
}
}
答案 0 :(得分:0)
感谢@Clemens,他对这个答案值得称赞。绑定语法不正确。它应该是
BindingOperations.SetBinding(MyRootControl, ItemsControl.ItemsSourceProperty, new Binding() { Source = this, Path= new PropertyPath("myData"), Mode = BindingMode.OneWay });