我正在尝试制作一个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
数据实体上寻找并且它不存在或不属于那里。
我已经尝试了几乎所有绑定属性的组合来IsReadOnly
绑定到 AddressControl
对象,但无法使其正常工作。
我已经尝试过这样的事情,但我无法IsReadOnly
独立绑定到AddressControl
属性而不是它的DataContext
.
<TextBox IsReadOnly="{Binding RelativeSource={RelativeSource Self}, Path=IsReadOnlyProperty}" Text="{Binding City, Mode=TwoWay}" />
我想我已经很接近了。我究竟做错了什么?