【发布时间】:2011-12-26 22:21:10
【问题描述】:
我正在编写一个控件库。在这个库中,有一些自定义面板填充了用户 UIElements。由于我的库中的每个子元素都必须具有“标题”属性,因此我编写了以下内容:
// Attached properties common to every UIElement
public static class MyLibCommonProperties
{
public static readonly DependencyProperty TitleProperty =
DependencyProperty.RegisterAttached(
"Title",
typeof(String),
typeof(UIElement),
new FrameworkPropertyMetadata(
"NoTitle", new PropertyChangedCallback(OnTitleChanged))
);
public static string GetTitle( UIElement _target )
{
return (string)_target.GetValue( TitleProperty );
}
public static void SetTitle( UIElement _target, string _value )
{
_target.SetValue( TitleProperty, _value );
}
private static void OnTitleChanged( DependencyObject _d, DependencyPropertyChangedEventArgs _e )
{
...
}
}
那么,如果我这样写:
<dl:HorizontalShelf>
<Label dl:MyLibCommonProperties.Title="CustomTitle">1</Label>
<Label>1</Label>
<Label>2</Label>
<Label>3</Label>
</dl:HorizontalShelf>
一切正常,属性获得指定的值,但如果我尝试将该属性绑定到其他一些 UIElement DependencyProperty,如下所示:
<dl:HorizontalShelf>
<Label dl:MyLibCommonProperties.Title="{Binding ElementName=NamedLabel, Path=Name}">1</Label>
<Label>1</Label>
<Label>2</Label>
<Label Name="NamedLabel">3</Label>
</dl:HorizontalShelf>
将引发异常:“不能在 'Label' 类型的 'SetTitle' 属性上设置 'Binding'。'Binding' 只能在 DependencyObject 的 DependencyProperty 上设置。”
我错过了什么?如果绑定到 MyLibCommonProperties 中定义的其他附加属性,而不是绑定到“名称”,则绑定似乎可以正常工作。
提前致谢。
【问题讨论】:
-
嗨,MyLibCommonProperties 必须从 DependecyObject 派生
-
只是猜测,但将您的 Get/SetTitle 第一个参数更改为 DependencyObject,而不是 UIElement。此外,在注册 Attache 属性时,第三个参数必须是附加属性的所有者,而不是所需的目标。将其更改为 MyLibCommonProperties。
-
什么是
HorizontalShelf?您是否在StackPanel或类似的内置控件中尝试过?其他一切似乎都很好。我只能假设HorizontalShelf是一个自定义控件,它不会将其子项识别为逻辑子项。见这里:kentb.blogspot.com/2008/10/customizing-logical-children.html
标签: c# wpf xaml binding attached-properties