如何将 ControlTemplate 中的控件 属性 数据绑定到包含此模板控件的 window 的数据上下文?

How to data-bind control's property within ControlTemplate, to the data-context of the window that contains the control with this template?

我有这个模板:

<ControlTemplate TargetType="Frame" x:Key="FrameControlTemplate">
    <!-- stuff, stuff, stuff, ... -->
        <Button Content="{Binding ButtonBackText}">
    <!-- stuff, stuff, stuff, ... -->
</ControlTemplate>

应用于此Frame

<Window ...>
    <Window.DataContext>
        <loc:MainWindowViewModel/>
    </Window.DataContext>
    <!-- stuff, stuff, stuff, ... -->
        <Frame Template="{StaticResource FrameControlTemplate}" />
    <!-- stuff, stuff, stuff, ... -->
</Window>

我需要 ControlTemplate 中的 Button 将其 Content 绑定到 window 的 DataContextMainWindowViewModel对象)。

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

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

我会将您的 Button 的 DataContext 直接设置为 window。

//Button constructor
public Controltemplate(){
   myButton.DataContext = Window.GetWindow(this);
}

此代码现在不会从任何父级继承任何 DataContext 并直接绑定到您的window


反对票更新:
我没有想到无法使用名称引用按钮。
但是,在模板中很容易做到这一点。

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_MyButton 设置为按钮的名称。

您还绑定到 Window 的 ButtonBackText - 您可能需要检查 Window 的 "Data Binding Error: ..." 以防 属性 在您的 Window 上不存在。