【问题标题】:How to bind to a WPF dependency property when the datacontext of the page is used for other bindings?当页面的数据上下文用于其他绑定时,如何绑定到 WPF 依赖属性?
【发布时间】:2010-10-20 18:52:36
【问题描述】:

当页面的数据上下文用于其他绑定时,如何绑定到 WPF 依赖属性? (简单问题)

【问题讨论】:

  • 您要求的不是您在 Google 搜索“WPF 数据绑定”时找到的内容吗?
  • 我正在寻找一个工作示例,其中页面的数据上下文已用于其他绑定。事实证明,元素的数据上下文需要设置为页面本身。如果需要,我将发布代码并编辑问题。

标签: wpf data-binding dependency-properties


【解决方案1】:

在 XAML 中:

Something="{Binding SomethingElse, ElementName=SomeElement}"

在代码中:

BindingOperations.SetBinding(obj, SomeClass.SomethingProperty, new Binding {
  Path = new PropertyPath(SomeElementType.SomethingElseProperty),  /* the UI property */
  Source = SomeElement /* the UI object */
});

虽然通常您会以相反的方式执行此操作,并将 UI 属性绑定到自定义依赖项属性。

【讨论】:

    【解决方案2】:

    需要设置元素的datacontext。

    XAML:

    <Window x:Class="WpfDependencyPropertyTest.Window1" x:Name="mywindow">
       <StackPanel>
          <Label Content="{Binding Path=Test, ElementName=mywindow}" />
       </StackPanel>
    </Window>
    

    C#:

    public static readonly DependencyProperty TestProperty =
            DependencyProperty.Register("Test",
                                        typeof(string),
                                        typeof(Window1),
                                        new FrameworkPropertyMetadata("Test"));
    public string Test
    {
       get { return (string)this.GetValue(Window1.TestProperty); }
       set { this.SetValue(Window1.TestProperty, value); }
    }
    

    另请参阅此相关问题:

    WPF DependencyProperties

    【讨论】:

    • Test 通过代码更改时,这是否会自动提供更改通知?
    • 你是我的救星,托马斯·布拉特
    • 我可以使用用户控制执行此操作吗?我尝试了同样的事情,但什么也没发生...... :(也许我错过了什么......
    猜你喜欢
    • 2023-03-26
    • 2012-11-08
    • 2010-10-09
    • 2014-08-31
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多