【发布时间】:2011-06-29 03:27:41
【问题描述】:
我的问题不是在UserControl 中连接DependencyProperties。这不是问题。当我将UserControl 中的按钮绑定到UserControl 的DependencyProperty 称为TargetCommand 时,当我在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,并且仍然保留与 TargetCommand 的 DependencyProperty 绑定?
【问题讨论】:
标签: c# wpf xaml datacontext dependency-properties