依存関係プロパティで 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 中国語 Web サイトの他の関連記事を参照してください。