访问DataTemplate控件层以外的资源

问题描述

  1. 在DataTemplate中添加一个Button,Button添加Command,但是Command无效
  2. 使用ContentControl的ContentTemplate,DataTemplate中按钮的绑定事件失效

问题产生的原因

Datatemplate无法访问到Datatemplate控件层以外的资源.

举例:ContextMenu在技术上是一个单独的窗口,所以它有自己的可视化树并且可能不包含在文档窗格的逻辑树中。因此,它不知道如何从包含视图中找到资源。

常见的两种办法

使用RelativeSource进行约束

你的DataTemplate看起来是在一个ItemsControl使用(如列表框),所以你说Command="{Binding NewProjectCommand}"将试图绑定到Task类型的属性,而你真的想绑定到父容器的属性。因此,您需要使用的RelativeSource约束力的,是这样的:

Command="{Binding Path=DataContext.NewProjectCommand, RelativeSource= 
     {RelativeSource FindAncestor, AncestorType={x:Type views:ProjectsView}}}" 

引用知道数据上下文的元素来获得对父DataContext的访问

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content={Binding MyLevel2Property}
              Command={Binding ElementName=level1Lister,
                       Path=DataContext.MyLevel1Command}
              CommandParameter={Binding MyLevel2Property}>
      </Button>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

原文链接

在DataTemplate中访问DataContext

WPF:无法从子控件访问静态资源

如何将WPF绑定与RelativeSource一起使用?

WPF:菜单项仅绑定一次命令参数

在WPF中将虚拟分支附加到逻辑树

登峰造极的成就源于自律
原文地址:https://www.cnblogs.com/fishpond816/p/13944683.html