WPF绑定同一控件的两个依赖属性,但需要两个数据上下文

WPF Binding two dependency properties of the same control but two datacontexts needed

我在一个网格中有两个控件。

   <TextBlock Text="{Binding Name}" TextAlignment="Center" />
   <TextBox Visibility="{Binding ElementName=EditMode,Source={Binding RelativeSource=
                   {RelativeSource FindAncestor, AncestorType={x:Type Window}}}, 
                   Converter={StaticResource BoolToVis}}"  Text="{Binding Name}" 
                   TextAlignment="Center" />

我正在尝试实现类似 editable/non 可编辑行为的功能。我知道我可能会选择 TextBox 并简单地更改 IsEditable 属性 但是,在我的场景中我仍然需要 DataContext,至少这就是我的想法。

在我的示例中,TextBlock 工作正常,TextBox 上的文本 属性 也工作正常,但对于可见性部分,我想绑定到数据 属性(EditMode 是一个布尔值)在其他层上找到。有没有办法将 DataContext 更改为该值,但仅限于 Visibility ?文本 属性 应该保持原样。

我是否应该尝试 hack,定义一个不可见的复选框,在单击我的编辑按钮时更改 IsChecked 并直接绑定到它?我会试试这个。我认为这样,不需要更改 DataContext。

在我看来,您已经差不多了,您应该可以使用 RelativeSource 来完成此操作。问题是您误用了 ElementName,ElementName 将绑定到命名源的 属性,并且会代替 RelativeSource 使用。您打算使用的是 Path,它是可选的,如下所示。

<TextBox Visibility="{Binding DataContext.EditMode, RelativeSource={RelativeSource AncestorType={x:Type Window}}, 
               Converter={StaticResource BoolToVis}}"
         Text="{Binding Name}" TextAlignment="Center" />

@FrumRoll 是正确的,您可以使用 RelativeSource Binding 访问不在集合 DataContext 对象中的 属性。但是,我不确定他们的代码是否正确...试试这个:

<TextBox Visibility="{Binding DataContext.EditMode, RelativeSource={RelativeSource 
    AncestorType={x:Type YourXamlPrefix:MainWindow}}}, Converter={StaticResource 
    BoolToVis}}" Text="{Binding Name}" TextAlignment="Center" />

显然,您需要使用本地 XAML 命名空间前缀更改 YourXamlPrefix 值,并使用 Window 的 name/type 更改 MainWindow 值如果不叫MainWindow。这还假设您的 EditMode 属性 已在 Window.

中定义

这个 可能 也可以,但不是专门寻找你的确切 Window,所以 可能 有一些问题:

<TextBox Visibility="{Binding DataContext.EditMode, RelativeSource={RelativeSource 
    AncestorType={x:Type Window}}}, Converter={StaticResource BoolToVis}}" 
    Text="{Binding Name}" TextAlignment="Center" />