2016-11-18 61 views
0

在UWP應用程序中,我試圖將ListBox插入到Content Control中。正如您將從我提交的代碼中看到的,ListBox的ItemsSource綁定不會向PropertyChanged事件註冊,因此當我嘗試將ItemsSource更改爲新集合時,它不會在列表中直觀地反映出來。我知道引用是正確的,因爲如果在設置綁定之前先創建新集合,屏幕將顯示列表。我需要做什麼才能使下面的代碼工作?無法在ContentControl中與ItemsControl綁定

<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

在派生自DependencyObject的類中實現INotifyPropertyChanged沒有任何意義。相反,'myData'應該是一個依賴屬性。目前,myData甚至不是屬性,而只是一個字段,因此不支持數據綁定。除此之外,目前還不清楚你想用它做什麼。 – Clemens

+0

@Clemens。道歉,當試圖將問題簡化爲這個簡單的代碼示例時,出現了一些令人難以置信的疏忽。我在原來的問題中糾正了這些問題,現在仍然存在。我試圖理解爲什麼在編寫內容控件時,更改ListBox集合並沒有體現出來。轉換爲依賴屬性不會回答這個問題。 – Sean

+0

實現INotifyPropertyChanged在這裏仍然沒有意義。除此之外,發射屬性名稱爲「myData」的PropertyChanged事件在這裏沒有效果,因爲你錯誤地設置了你的綁定。 'Binding.Source'應該是擁有屬性('this')的對象,並且'Binding.Path'應該被設置爲'new PropertyPath(「myData」)'。 – Clemens

回答

0

感謝@Clemens,誰對這個答案的功勞。綁定語法不正確。它應該是

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