【问题标题】:Using C#, how to access a control inside WPF ResourceDictionary使用 C#,如何访问 WPF ResourceDictionary 中的控件
【发布时间】:2020-10-18 15:49:13
【问题描述】:

我有一个ResourceDictionary 来定义我的自定义窗口样式。我正在使用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>

【问题讨论】:

    标签: c# wpf resourcedictionary


    【解决方案1】:

    您没有说明如何/何时应用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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多