sách gpt4 ăn đã đi

c# - : Bind to a UserControl's DependencyProperty, 当 UserControl 有一个 DataContext 时如何?

In lại Tác giả: Walker 123 更新时间:2023-11-30 16:31:13 27 4
mua khóa gpt4 giày nike

我的问题是没有在 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?

câu trả lời hay nhất

您的 PathToCommand 定义在哪里?如果我正确地阅读了您的示例,它在 VisualTree 中的位置应该高于 UserControl。在这种情况下,您将绑定(bind)到具有包含 PathToCommand 的 DataContext 的任何控件,并绑定(bind)到 DataContext.PathToCommand




TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />

关于c# - : Bind to a UserControl's DependencyProperty, 当 UserControl 有一个 DataContext 时如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5030128/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress