1

我正在尝试制作一个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中断。不足为奇,因为它IsReadOnlyAddress数据实体上寻找并且它不存在或不属于那里。

我已经尝试了几乎所有绑定属性的组合来IsReadOnly绑定到 AddressControl对象,但无法使其正常工作。

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

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

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

4

2 回答 2

1

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

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

于 2010-03-27T03:32:09.723 回答
0

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

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

于 2009-12-17T22:10:15.553 回答