繁体   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