[英]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>
应用程序.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>
您没有展示如何/何时应用Style
。 假设您直接在 XAML 文件中设置FrameworkElement.Style
,您应该能够在引发FrameworkElement.Loaded
时获取模板元素:
主窗口.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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.