【问题标题】:Binding property to Silverlight dependency property independent of DataContext将属性绑定到独立于 DataContext 的 Silverlight 依赖项属性
【发布时间】:2010-12-27 05:25:32
【问题描述】:

我正在尝试创建一个具有IsReadOnly 属性的Address 控件,这将使内部的每个TextBox 在设置为true 时只读。

 <my:AddressControl Grid.Column="1" Margin="5" IsReadOnly="True"/>

我已经设法使用依赖属性很好地做到了这一点,并且它可以工作。

这是一个声明了依赖属性的简单类:

public partial class AddressControl : UserControl
{
    public AddressControl()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public static readonly DependencyProperty IsReadOnlyProperty = 
       DependencyProperty.Register("IsReadOnly", typeof(bool), 
                                   typeof(AddressControl), null);

    public bool IsReadOnly
    {
        get { return (bool)GetValue(IsReadOnlyProperty); }
        set { SetValue(IsReadOnlyProperty, value); }
    }
}

在此代码隐藏文件的 XAML 中,每个地址行都有一个 Textbox

  <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding City, Mode=TwoWay}"/>
  <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding State, Mode=TwoWay}"/>
  <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding Zip, Mode=TwoWay}"/>

就像我说的那样,这很好用。 问题是Address 控件本身绑定到其父对象(我有几个要绑定的地址)。

 <my:AddressControl DataContext="{Binding ShippingAddress, Mode=TwoWay}" IsReadOnly="True">
 <my:AddressControl DataContext="{Binding BillingAddress, Mode=TwoWay}" IsReadOnly="True">

问题是,一旦我将DataContext 设置为'this' 以外的其他值,IsReadOnly 的绑定就会中断。这并不奇怪,因为它在 Address 数据实体上寻找 IsReadOnly,但它不存在或不属于那里。

我几乎尝试了binding attributes 的所有组合以使IsReadOnly 绑定到AddressControl obejct,但无法使其正常工作。

我已经尝试过这样的事情,但我无法让IsReadOnly 独立绑定到AddressControl 属性而不是它的DataContext

<TextBox IsReadOnly="{Binding RelativeSource={RelativeSource Self}, Path=IsReadOnlyProperty}" Text="{Binding City, Mode=TwoWay}" />

我想我已经很接近了。我做错了什么?

【问题讨论】:

  • 使用了“Text”属性的绑定工具后,“RelativeSource Self”似乎实际上意味着绑定到 TextBox 本身——这不是我想要的。因此,我认为我需要 Silverlight 中尚不存在的 FindAncestor :-( 我想我被卡住了?connect.microsoft.com/VisualStudio/feedback/…

标签: silverlight silverlight-4.0 wcf-binding


【解决方案1】:

至少,如果您只想通过绑定来做到这一点,我认为您会遇到困难。我的猜测是,您将不得不求助于代码隐藏,大概是通过迭代您的子文本框控件并将其 IsReadOnly 属性设置为地址控件的 IsReadOnly 属性的副作用。

不像有些人认为代码隐藏文件中的任何代码实际上都是在承认失败,我对此并不信奉:如果将一些代码放入代码隐藏文件是做某事的最简单方法,这就是我放置代码的地方。相反,如果我必须花半天时间试图弄清楚如何通过绑定来做某事,而我可以在五分钟内使用代码隐藏来做某事,那是失败,IMO。

【讨论】:

  • 如果我被卡住了,我会找到 - 只是不想错过任何东西。即使您最初确实浪费了一些时间,这些学习经验也可以帮助您更好地理解框架。绝对同意事情的代码隐藏方面 - 在这里查看我的帖子stackoverflow.com/questions/489415/…
【解决方案2】:

With this answer(实际上是我自己对类似问题的回答)我有一个很好的 [更好] 解决方案。

我仍然需要遍历文本框,但我不必设置实际值。我可以在代码隐藏中创建绑定——只是不能使用 XAML。

【讨论】:

  • 就像说这是正确的方法,而标记的答案是错误的——这是可能的,你没有被卡住。
  • 哦,我刚刚意识到这是我的问题,所以我可以更改答案。大声笑
  • 我认为 ken 的意思是你不能只使用 XAML 绑定来做到这一点 - 但幸运的是它可以在代码中创建绑定
猜你喜欢
  • 2013-03-30
  • 1970-01-01
  • 2011-07-29
  • 2014-09-22
  • 2011-07-23
  • 2010-12-16
  • 1970-01-01
  • 2012-07-11
  • 2016-01-22
相关资源
最近更新 更多