Wpf 如何绑定控件';控件模板中的属性,指向包含具有此模板的控件的窗口的数据上下文?

Wpf 如何绑定控件';控件模板中的属性,指向包含具有此模板的控件的窗口的数据上下文?,wpf,xaml,mvvm,data-binding,controltemplate,Wpf,Xaml,Mvvm,Data Binding,Controltemplate,我有这个模板: <ControlTemplate TargetType="Frame" x:Key="FrameControlTemplate"> <!-- stuff, stuff, stuff, ... --> <Button Content="{Binding ButtonBackText}"> <!-- stuff, stuff, stuff, ... --> </ControlTemplate>

我有这个模板:

<ControlTemplate TargetType="Frame" x:Key="FrameControlTemplate">
    <!-- stuff, stuff, stuff, ... -->
        <Button Content="{Binding ButtonBackText}">
    <!-- stuff, stuff, stuff, ... -->
</ControlTemplate>
我需要
控件模板中的
按钮
将其
内容
绑定到窗口的
数据上下文
(对象
MainWindowViewModel


出于某种原因,它没有显示文本。这是为什么?

您基本上依赖于DataContext继承,这似乎不是一个很好的解决方案,因为您使用的是一个框架,无法确定该框架之外的内容。很可能有人甚至你在框架之外的某个地方更改了DataContext

我会将按钮的DataContext直接设置到窗口

//Button constructor
public Controltemplate(){
   myButton.DataContext = Window.GetWindow(this);
}
此代码现在将从任何父级继承任何DataContext,并直接绑定到您的窗口


否决时更新:
我没有想到不能使用该名称参照按钮。
然而,在模板中实现这一点非常容易

private Button _partButton = null;

public ControlTemplate{
   Loaded += (sender, e) => OnLoaded();
}

private void OnLoaded(){
   _partButton  = (Button)Template.FindName("PART_MyButton"); //You "should" use PART_ as a prefix in a Template
  if(_partButton  != null)
     _partButton.DataContext = Window.GetWindow(this);
}
只需确保您还将
PART\u MyButton
设置为按钮的名称。


此外,您正在绑定到窗口的
按钮BackText
——如果窗口中不存在该属性,您可能需要检查输出窗口中的“数据绑定错误:…”

通常我会说,您可以使用
RelativeSource
绑定来实现这一点,但它应该在您提供的XAML中按原样工作,除非stuff中有更改其项的默认
DataContext
,例如
ItemsControl
。因此,不知道这里是否存在更大的问题,也不清楚模板中的按钮是其子成员还是独立兄弟。您需要在一个新项目中提供一个实际的示例,我们可以使用它来复制问题,并随后提供一个答案。应该很有启发性。我明白为什么有人否决了你,你的逻辑的最初想法是正确的,但应用程序是错误的,因为在控件模板中没有使用“名称”,因此在代码隐藏中没有可以直接访问的“myButton”。@OmegaMan Ups,快速修复方法并不总是像预期的那样有效:D更新了我的答案
private Button _partButton = null;

public ControlTemplate{
   Loaded += (sender, e) => OnLoaded();
}

private void OnLoaded(){
   _partButton  = (Button)Template.FindName("PART_MyButton"); //You "should" use PART_ as a prefix in a Template
  if(_partButton  != null)
     _partButton.DataContext = Window.GetWindow(this);
}