【发布时间】:2012-08-01 09:40:58
【问题描述】:
我尝试创建一个依赖属性“IsReadOnly”,以便在某些事件之后自动将表单中的所有文本框设置为只读。
该属性是在我的窗口后面的代码中设置的,带有文本框,如下所示:
public static readonly DependencyProperty IsReadOnlyProperty =
DependencyProperty.Register("IsReadOnly",
typeof(bool),
typeof(MainWindow),
new PropertyMetadata());
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
文本框的 Xaml 代码与此类似:
<TextBox Text="{numBind:NumericFormatBinding Path=BudgetStatement.OpExpTotalByFunction}"
IsReadOnly="{Binding Path=IsReadOnly,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window},
Mode=TwoWay}"
Name="txtOpExpByProgram" />
但它不起作用。我仍然可以在文本框中编辑值。我收到以下输出错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'IsReadOnly' property not found on 'object' ''ListCollectionView' (HashCode=54963679)'. BindingExpression:Path=IsReadOnly; DataItem='ListCollectionView' (HashCode=54963679); target element is 'TextBox' (Name=''); target property is 'IsReadOnly' (type 'Boolean')
我不知道足够的 wpf 来正确理解这个错误,但它似乎与 ListCollectionView 有关 - 但我没有尝试将属性附加到 ListCollectionView 所以我被卡住了。
谷歌搜索表明这可能是由于 DataContext 和依赖属性需要特殊处理 (http://stackoverflow.com/questions/8497841/dependency-property-and-binding-error),或者 PropertyMetaData 应该是一个框架(或 UI)PropertyMetaData。
谁能指出我正确的方向以找出什么不起作用?
tia
亚历克斯
ps: numbind 只是在所有文本框中设置字符串格式
【问题讨论】:
-
这个依赖属性定义在什么类上?
-
@bob:BudgetMainWindow。 - 它位于包含文本框的窗口的代码隐藏
-
那么您的 AncestorType 不需要是
BudgetMainWindow而不是 window 吗? -
BudgetMainWindow 可能是一个窗口,所以它应该可以工作。但我也不确定。
-
将祖先类型更改为 BudgetMainWindow。得到这个异常:类型引用找不到名为“{schemas.microsoft.com/winfx/2006/xaml/presentation}BudgetMainWindow”的类型。
标签: wpf data-binding dependency-properties