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 に答える