将属性绑定到独立于DataContext的Silverlight依赖项属性

时间:2009-12-16 12:20:33

标签: silverlight silverlight-4.0 wcf-binding

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

 <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的绑定就会中断。不足为奇,因为它在IsReadOnly数据实体上查找Address并且它不存在或属于那里。

我已经尝试了binding attributes的每个组合,以使IsReadOnly绑定到AddressControl obejct但无法使其正常工作。

我尝试过这样的事情,但我不能让IsReadOnly独立地绑定到AddressControl属性而不是DataContext

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

我觉得我很亲密。我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我认为,如果你想通过绑定这样做,你至少会陷入困境。我的猜测是你将不得不求助于代码隐藏,可能是通过迭代你的子文本框控件并将它们的IsReadOnly属性设置为你的地址控件的IsReadOnly属性的副作用。

与那些认为代码隐藏文件中的任何代码实际上是承认失败的人不同,我不会对此有所了解:如果将一些代码放入代码隐藏中是最简单的方法,这就是我放置代码的地方。相反,如果我不得不花半天的时间试图找出如何通过绑定来做一些事情,我可以在五分钟内完成代码隐藏,那是失败,IMO。