我的问题是没有在 UserControl
中连接 DependencyProperties
。这不是问题。当我将 UserControl
中的按钮绑定(bind)到 UserControl
của DependencyProperty
称为 TargetCommand
时,当我在 UserControl
上设置一个 DataContext
。我试过使用 FindAncestor
,当然还有 ElementName
,但它们仅在 UserControl
上没有 DataContext
时起作用>.
有解决办法吗?
例子:
主窗口
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 ); }
}
我的用户控件 - Xaml
只要未在主窗口中的 MyUserControl 上设置 DataContext,MyUserControl 中绑定(bind)的 RelativeSource 和 ElementName 方法都会正确连接。一旦设置了 DataContext,两者都不起作用。
有没有办法在 MyUserControl 上设置 DataContext,并且仍然保留绑定(bind)到 TargetCommand 的 DependencyProperty?
您的 PathToCommand
定义在哪里?如果我正确地阅读了您的示例,它在 VisualTree 中的位置应该高于 UserControl。在这种情况下,您将绑定(bind)到具有包含 PathToCommand 的 DataContext 的任何控件,并绑定(bind)到 DataContext.PathToCommand
TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />
Tôi là một lập trình viên xuất sắc, rất giỏi!