종속성 속성에서 XAML 바인딩이 실패함
종속성 속성에 대한 데이터 바인딩은 XAML에서는 효과가 없지만 코드 숨김에서는 잘 작동합니다. 다음 코드 조각은 문제를 보여줍니다.
<code class="language-xml"><UserControl ...="" x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test}"/> </UserControl></code>
종속성 속성은 다음과 같이 정의됩니다.
<code class="language-csharp">public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT")); public string Test { get { return (string)GetValue(TestProperty); } set { SetValue(TestProperty, value); } }</code>
기본 창에서는 일반 속성에 대한 바인딩이 완벽하게 작동합니다.
<code class="language-xml"><TextBlock Text="{Binding MyText}"/></code>
그러나 사용자 컨트롤의 동일한 바인딩은 텍스트를 업데이트하지 않습니다.
<code class="language-xml"><MyControl Test="{Binding MyText}" x:Name="TheControl"/></code>
코드 숨김으로 구현할 때 바인딩이 제대로 작동한다는 점은 주목할 가치가 있습니다.
<code class="language-csharp">TheControl.SetBinding(MyControl.TestProperty, new Binding { Source = DataContext, Path = new PropertyPath("MyText"), Mode = BindingMode.TwoWay });</code>
해결책:
올바른 종속성 속성 선언:
<code class="language-csharp">public static readonly DependencyProperty TestProperty = DependencyProperty.Register( nameof(Test), typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));</code>
UserControl XAML 바인딩:
<code class="language-xml"><UserControl ...="" x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </UserControl></code>
UserControl 생성자에서 DataContext 설정 방지:
UserControl의 생성자에서 DataContext를 설정하지 마십시오. 이렇게 하면 UserControl이 해당 부모의 DataContext를 상속하지 못하게 됩니다.
위 내용은 XAML 바인딩이 종속성 속성에서는 작동하지 않지만 코드 숨김에서는 작동하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!