使用 C#,如何访问 WPF ResourceDictionary 中的控件

Using C#, how to access a control inside WPF ResourceDictionary

我有一个 ResourceDictionary 来定义我的自定义 Window 样式。我正在使用 WindowChrome 通过向其添加具有按钮控件的自定义标题栏来设置 MainWindow 的样式。 问题:在代码隐藏文件 MainWindow.cs 中使用 C#,如何访问位于以下 MyWindowChrome.xaml 中的按钮控件 btnTest文件:

MyWindowChrome.xaml:

<ResourceDictionary x:Class="MyWPFProject.WindowStyle"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:local="clr-namespace:MyWPFProject">
    
    <Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="WindowChrome.WindowChrome">
            <Setter.Value>
                <WindowChrome ResizeBorderThickness="5" UseAeroCaptionButtons="False" />
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Window}">
                    <Grid>
                        <DockPanel>
                            <Button x:Name="btnTest" WindowChrome.IsHitTestVisibleInChrome="True"/>
                        </DockPanel>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

App.xaml

<Application x:Class="MyWPFProject.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:main="clr-namespace:MyWPFProject"
                 StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MyWPFProject;component/WindowStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

您没有显示 how/when 您应用了 Style。假设你直接在 XAML 文件中设置 FrameworkElement.Style,你应该能够在引发 FrameworkElement.Loaded 时获取模板元素:

MainWindow.xaml.cs

partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    this.Loaded += OnLoaded;
  }

  private void OnLoaded(object sender, RoutedEventArgs e)
  {
    var button = this.Template.FindName("btnTest", this) as Button;
  }
}