0

在 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;
    }
}
4

1 回答 1

0

感谢@Clemens,他的回答值得称赞。绑定语法不正确。它应该是

            BindingOperations.SetBinding(MyRootControl, ItemsControl.ItemsSourceProperty, new Binding() { Source = this, Path= new PropertyPath("myData"), Mode = BindingMode.OneWay });
于 2016-11-21T20:49:52.643 回答