首页> C#>如何:绑定到用户控件的DependencyProperty,当用户控件具有DataContext?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了首页> C#>如何:绑定到用户控件的DependencyProperty,当用户控件具有DataContext?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1747字,纯文字阅读大概需要3分钟。
内容图文
![首页> C#>如何:绑定到用户控件的DependencyProperty,当用户控件具有DataContext?](/upload/InfoBanner/zyjiaocheng/653/5354ab10ba19468cbe4df8e401b92108.jpg)
我的问题不是在UserControl中连接DependencyProperties.这不是问题.当我将UserControl中的按钮绑定到名为TargetCommand的UserControl的DependencyProperty时,在UserControl上设置DataContext时,绑定会中断.我尝试使用FindAncestor和ElementName,但是它们仅在UserControl上没有DataContext时起作用.
有没有解决的办法?
例:
主视窗
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid>
<UserControls:MyUserControl
TargetCommand="{Binding PathToCommand}"
DataContext="{Binding PathToSomeModel}" />
后面的MyUserControl代码
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty TargetCommandProperty =
DependencyProperty.Register( "TargetCommand", typeof( ICommand ), typeof( MyUserControl ) );
public ICommand TargetCommand
{
get { return (ICommand)GetValue( TargetCommandProperty ); }
set { SetValue( TargetCommandProperty, value ); }
}
MyUserControl-Xaml
<UserControl x:Name="root">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=TargetCommand}" />
<Button Command="{Binding Path=TargetCommand, ElementName=root}" />
只要未在MainWindow的MyUserControl上设置DataContext,MyUserControl中的RelativeSource和ElementName绑定方法都可以正确连接.设置DataContext后,两者均无效.
有没有一种方法可以在MyUserControl上设置DataContext,并且仍然保留DependencyProperty绑定到TargetCommand?
解决方法:
您的PathToCommand在哪里定义?如果我正确地阅读了您的示例,则它在VisualTree中的位置应该比UserControl高.在这种情况下,您将绑定到具有包含包含PathToCommand的DataContext的任何控件,并绑定到DataContext.PathToCommand
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid x:Name="PART_Root">
<UserControls:MyUserControl
TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />
内容总结
以上是互联网集市为您收集整理的首页> C#>如何:绑定到用户控件的DependencyProperty,当用户控件具有DataContext?全部内容,希望文章能够帮你解决首页> C#>如何:绑定到用户控件的DependencyProperty,当用户控件具有DataContext?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。