[英]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.