ホームページ >バックエンド開発 >C++ >XAML バインディングが依存関係プロパティでは機能しないのに、コードビハインドでは機能するのはなぜですか?

XAML バインディングが依存関係プロパティでは機能しないのに、コードビハインドでは機能するのはなぜですか?

Patricia Arquette
Patricia Arquetteオリジナル
2025-01-09 21:11:45567ブラウズ

Why Doesn't My XAML Binding Work on a Dependency Property, But Works in Code-Behind?

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

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。