0
UWP 앱에서 ListBox를 콘텐츠 컨트롤에 삽입하려고합니다. 내가 제출하는 코드에서 볼 수 있듯이 ListBox의 ItemsSource 바인딩은 PropertyChanged 이벤트에 등록되지 않으므로 ItemsSource를 새 컬렉션으로 변경하려고하면 시각적으로 목록에 반영되지 않습니다. 바인딩을 설정하기 전에 새 컬렉션을 먼저 작성하면 화면에 목록이 표시되므로 참조가 올바른지 확인합니다. 다음 코드가 작동하도록하려면 어떻게해야합니까? 이 답변에 대한 크레딧을받을 권리가 @Clemens에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;
}
}
DepotencyObject에서 파생 된 클래스에서 INotifyPropertyChanged를 구현하는 것은 이치에 맞지 않습니다. 대신에, myData는 의존성 프로퍼티 여야한다. 현재 myData는 속성이 아니라 필드이기 때문에 데이터 바인딩을 지원하지 않습니다. 그 외에도, 당신이 무엇을하려고하는지 명확하지 않습니다. – Clemens
@ 크레멘. 죄송합니다,이 간단한 코드 예제에 문제를 압축하려고 할 때 몇 가지 심각한 실수가있었습니다. 나는 여전히 존재하는 원래의 질문에서이 이슈들을 수정했다. ListBox 컬렉션을 변경하면 내용 컨트롤에 반영되지 않는 이유를 이해하려고합니다. 종속성 속성으로 변환하면이 질문에 답할 수 없습니다. – Sean
INotifyPropertyChanged를 구현하는 것은 여전히 의미가 없습니다. 그 외에도 바인딩을 잘못 설정했기 때문에 속성 이름 "myData"로 PropertyChanged 이벤트를 발생시키는 것은 아무런 효과가 없습니다. 'Binding.Source'는 속성 ('this')을 소유 한 객체 여야하며,'Binding.Path'는'new PropertyPath ("myData")'로 설정되어야합니다. – Clemens