我正在写一个控件库。在这个库中有一些用户UIElements填充的自定义面板。因为在我的lib每个子元素必须有一个“标题”属性,我写了下面:无法将附加属性绑定到其他依赖项属性
// 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>
一个异常将会被抛出:“一个‘绑定’不能在‘的setTitle’属性设置类型'标签'。 A“绑定”只能DependencyObject的一个DependencyProperty设置。”
我缺少什么?绑定似乎如果不是绑定到做工精细‘名称’我绑定到MyLibCommonProperties定义的其它一些附加属性。
在此先感谢。
嗨,MyLibCommonProperties必须从DependecyObject – 2011-11-11 10:59:36
只是一个猜测得到,但改变你的读/第一的setTitle参数的DependencyObject,不是的UIElement 。在注册您的Attache属性时,第三个参数必须是所附属性的所有者,而不是所需的目标。将其更改为MyLibCommonProperties。 – dowhilefor
什么是'HorizontalShelf'?你是否在'StackPanel'或类似的内置控件中尝试过?其他一切似乎都很好。我只能假设'HorizontalShelf'是一个自定义控件,它不会将其子项识别为逻辑子项。看到这里:http://kentb.blogspot.com/2008/10/customizing-logical-children.html –