簡體   English   中英

無法與ContentControl中的ItemsControl形成綁定

[英]Cannot form binding with ItemsControl inside ContentControl

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

感謝@Clemens,這個答案值得稱贊。 綁定語法不正確。 它應該是

            BindingOperations.SetBinding(MyRootControl, ItemsControl.ItemsSourceProperty, new Binding() { Source = this, Path= new PropertyPath("myData"), Mode = BindingMode.OneWay });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM