재사용 가능한 UserControl을 개발하려고하지만 바인딩 문제가 발생합니다. 내가 테스트 할 수 있지만 그것을 밖으로 정렬 할 수없는 작은 응용 프로그램을 만들었습니다, 또는 적어도 그것이 내가 예상했던대로 작동하지 않는 이유를 이해합니다.WPF UserControl이 부모 DataContext를 상속하지 않습니다.
코드는 다음과 같습니다. MainWindow.xaml에 넣은 TestUserControl의 인스턴스는 TextBlock 에서처럼 DataContext를 상속받습니다. 대신 DataContext가 null 인 것으로 보입니다. DataContext가 전달되지 않는 이유가 있습니까? 자동으로 설정해야합니까?
MainWindow.xaml
<Window x:Class="WpfTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTestApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Vertical">
<local:TestUserControl TextFromParent="{Binding SomeText}" />
<TextBlock Name="TestTextBlock" Text="{Binding SomeText}" />
</StackPanel>
</Window>
MainWindow.xaml.cs를
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfTestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _someText;
public MainWindow()
{
DataContext = this;
InitializeComponent();
SomeText = "New Text!";
}
public string SomeText
{
get { return _someText; }
set
{
_someText = value;
NotifyOnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyOnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
TestUserControl.xaml
<UserControl x:Class="WpfTestApp.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfTestApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock Name="TheTextBlock" Text="{Binding TextFromParent}" />
</Grid>
</UserControl>
TestUserControl.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace WpfTestApp
{
public partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
}
public string TextFromParent
{
get { return (string)GetValue(TextFromParentProperty); }
set { SetValue(TextFromParentProperty, value); }
}
public static readonly DependencyProperty TextFromParentProperty = DependencyProperty.Register(
"TextFromParent", typeof(string), typeof(TestUserControl), new PropertyMetadata());
}
}
012 3,516,
프로그램이 작동 바인딩 TextBlock에 의해 빈 다음에 다음과 같은 실행, 첫 번째 텍스트 다음과 같습니다