首页 >后端开发 >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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn