C# Can';t将附加属性绑定到另一个依赖属性
我正在写一个控制库。在该库中,有一些自定义面板,这些面板由用户UI元素填充。由于lib中的每个子元素都必须具有“Title”属性,因此我编写了以下代码:C# Can';t将附加属性绑定到另一个依赖属性,c#,wpf,xaml,binding,attached-properties,C#,Wpf,Xaml,Binding,Attached Properties,我正在写一个控制库。在该库中,有一些自定义面板,这些面板由用户UI元素填充。由于lib中的每个子元素都必须具有“Title”属性,因此我编写了以下代码: // Attached properties common to every UIElement public static class MyLibCommonProperties { public static readonly DependencyProperty TitleProperty = Dependency
// 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>
1.
1.
2.
3.
一切正常,属性获得指定的值,但如果我尝试将该属性绑定到其他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>
1.
1.
2.
3.
将引发异常:“无法在“Label”类型的“SetTitle”属性上设置“Binding”。只能在DependencyObject的DependencyProperty上设置“Binding”
我错过了什么?如果我绑定到MyLibCommonProperties中定义的其他附加属性,而不是绑定到“Name”,那么绑定似乎可以正常工作
提前感谢。将DependencyProperty定义中的
UIElement
替换为MyLibCommonProperties
public static readonly DependencyProperty TitleProperty =
DependencyProperty.RegisterAttached(
"Title",
typeof(String),
typeof(MyLibCommonProperties), // Change this line
new FrameworkPropertyMetadata(
"NoTitle", new PropertyChangedCallback(OnTitleChanged))
);
我认为这可能是因为绑定隐式地使用了指定的父类来调用SetTitle()
,所以它调用的是Label.SetTitle()
,而不是MyLibCommonProperties.SetTitle()
我对一些自定义文本框属性也有同样的问题。如果使用
typeof(TextBox)
则无法绑定到该值,但如果使用typeof(TextBoxHelpers)
则可以Hi,MyLibCommonProperties必须从DependencyObjects派生只是猜测,但将Get/SetTitle first参数更改为DependencyObject,而不是UIElement。此外,在注册Attache属性时,第三个参数必须是附加属性的所有者,而不是所需的目标。将其更改为MyLibCommonProperties。什么是HorizontalShelf
?您是否在StackPanel
或类似的内置控件中试用过?其他一切似乎都很好。我只能假设HorizontalShelf
是一个自定义控件,它不能将其子项识别为逻辑子项。看这里:瑞秋,这不是你的答案第一次帮助我了!(我相信这不会是最后一次)。甚至在差不多十年之后。@Uudddllrss哦,哇,我真不敢相信已经快十年了!现在我觉得自己老了,哈哈,我很高兴我的答案仍然有用