【发布时间】: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