Binding property to Silverlight dependency property independent of DataContext

Posted by Simon_Weaver on Stack Overflow See other posts from Stack Overflow or by Simon_Weaver
Published on 2009-12-16T12:20:33Z Indexed on 2010/03/27 3:43 UTC
Read the original article Hit count: 720

I'm trying to make an Address control that has an IsReadOnly property, which will make every TextBox inside read only when set to true.

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

I've managed to do this just fine with a dependency property and it works.

Here's a simple class with the dependency property declared :

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); }
    }
}

In the XAML for this codebehind file I have a Textbox for each address line:

  <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}"/>

Like i said this works just fine. The problem is that the Address control itself is bound to its parent object (I have several addresses I am binding).

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

The problem is that as soon as I set DataContext to something other than 'this' then the binding for IsReadOnly breaks. Not surprising because its looking for IsReadOnly on the Address data entity and it doesn't exist or belong there.

I've tried just about every combination of binding attributes to get IsReadOnly to bind to the AddressControl obejct but can't get it working.

I've tried things like this, but I can't get IsReadOnly to bind independently to the AddressControl property instead of its DataContext.

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

I think I'm pretty close. What am I doing wrong?

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about wcf-binding