WPF ユーザー コントロール: 依存関係プロパティに関する XAML バインドの問題
WPF ユーザー コントロールの XAML 内で依存関係プロパティにバインドするのは難しい場合があります。 一般的なシナリオを調べてみましょう:
TextBlock を使用したユーザー コントロール:
<UserControl ... x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test}" /> </UserControl>
ユーザー コントロールの依存関係プロパティ:
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); } }
MainWindow ViewModel (または DataContext):
private string _myText = "default"; public string MyText { get { return _myText; } set { _myText = value; NotifyPropertyChanged(); } }
MainWindow でのバインド (成功):
<TextBlock Text="{Binding MyText}" />
ユーザー コントロールでのバインド (失敗):
<MyControl Test="{Binding MyText}" />
分離コード バインディング (成功):
TheControl.SetBinding(MyControl.TestProperty, new Binding { Source = DataContext, Path = new PropertyPath("MyText"), Mode = BindingMode.TwoWay });
根本原因:
バインディング ソースが明示的に定義されていないため、ユーザー コントロール内の XAML バインディングは失敗します。 デフォルトはユーザー コントロール独自のプロパティです。
解決策:
RelativeSource
を使用してバインディング ソースを指定します:
<UserControl ... x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /> </UserControl>
これは、UserControl
プロパティの Test
型の祖先を検索するようにバインディングに明示的に指示します。 あるいは、データ コンテキストがウィンドウ レベルにある場合は、AncestorType={x:Type Window}
を使用できます。
重要な考慮事項:
DataContext
を設定することは一般的に推奨されず、バインドの問題が発生する可能性があります。これらのガイドラインに従うことで、WPF ユーザー コントロール内の依存関係プロパティに確実にバインドできます。
以上がXAML バインドが WPF ユーザー コントロールの依存関係プロパティで機能しないのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。