自定义用户控件属性绑定失败 silverlight
我有一个自定义用户控件 DataContext="{BindingrelativeSource={RelativeSource self}}"
在后面的代码中,我创建了一个依赖属性,例如:
public static DependencyProperty ElementNameProperty = DependencyProperty.Register("ElementName",
typeof(string),
typeof(ElementControl),
new PropertyMetadata(new PropertyChangedCallback((s, e) => { new Base().OnPropertyChanged("ElementName"); })));
public string ElementName
{
get
{
return (string)base.GetValue(ElementNameProperty);
}
set
{
base.SetValue(ElementNameProperty, value);
}
}
现在,当我尝试在主页中使用此用户控件时.xaml 并使用以下绑定:
,它会继续在我的自定义用户控件中搜索“name”属性,而不是它应该出现的位置 从?
我做错了什么?
I have a custom usercontrol with DataContext="{Binding RelativeSource={RelativeSource self}}"
On the code behind i've made a dependency property like:
public static DependencyProperty ElementNameProperty = DependencyProperty.Register("ElementName",
typeof(string),
typeof(ElementControl),
new PropertyMetadata(new PropertyChangedCallback((s, e) => { new Base().OnPropertyChanged("ElementName"); })));
public string ElementName
{
get
{
return (string)base.GetValue(ElementNameProperty);
}
set
{
base.SetValue(ElementNameProperty, value);
}
}
Now when I try to use this usercontrol in my mainpage.xaml and use the following binding: <test.TestControl ElementName="{Binding name}" />
, it keeps searching for 'name' property in my custom usercontrol instead of where it should come from?
What am I doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在那里进行搜索,因为您在用户控件的最顶层设置了
DataContext
。您需要做的是摆脱用户控件中与 self 的相对绑定,并在绑定中指定 ElementName (在用户控件内)。顺便说一句,您可能不需要PropertyChangedCallback
中的OnPropertyChanged
因为DependencyProperties
本质上会通知值更改。It searches there because you have the
DataContext
set on the topmost level for your user control. What you would need to do is get rid of the relative binding to self in the user control and specify ElementName in bindings (inside user control). Btw you probably don't needOnPropertyChanged
in thePropertyChangedCallback
causeDependencyProperties
in their nature notify about value changes.我最终是这样解决的。这不是我想要的方式,但它(在我看来)是一个非常巧妙的解决方案。
CustomUserControl.xaml
CustomUserControl.xaml.cs
I eventually solved it this way. Not the way I wanted, but it's a (in my eyes) pretty neat solution.
CustomUserControl.xaml
CustomUserControl.xaml.cs