我正在编写一个控件库。在这个库中,有一些自定义面板,这些面板中填充了用户的UI元素。由于我的库中的每个子元素都必须有一个“标题”属性,因此我编写了以下代码:
// 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>
如果将“Name”绑定到MyLibCommonProperties中定义的其他附加属性,则绑定似乎可以正常工作。但是,如果尝试将“Binding”设置到“Label”的“SetTitle”属性上,则会抛出异常:“无法在类型为'Label'的'SetTitle'属性上设置'Binding'。只能在DependencyObject的DependencyProperty上设置'Binding'。”
请问我遗漏了什么?提前感谢。
HorizontalShelf
是什么?你是否尝试在StackPanel
或类似的内置控件中使用它?其他一切看起来都很好。我只能假设HorizontalShelf
是一个自定义控件,无法将其子元素识别为逻辑子元素。请参见此处:http://kentb.blogspot.com/2008/10/customizing-logical-children.html - Kent Boogaart