c# - 如何从其隐藏代码访问资源字典中的控件?

标签 c# wpf resourcedictionary windowless

我有一个无窗口应用程序,它只包含一个由 ResourceDictionary 填充的 App.xaml。如何从其代码隐藏访问该词典中的控件?

最佳答案

尝试了各种方法都不行,比如通过VisualTreeHelper获取控件,直接通过名称访问控件,解决方法出奇的简单:

ResourceDictionary.xaml

<ResourceDictionary x:Class="My.Namespace"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Button x:Key="myButtonName" />

</ResourceDictionary>

ResourceDictionary.xaml.cs:

// Example with a button control
Button myButton= this["myButtonName"] as Button;

if(myButton != null)
{
 // Do something
}

关于c# - 如何从其隐藏代码访问资源字典中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420676/

相关文章:

只能设置一次的 C# 常量属性

c# - 如何让 ffmpeg 在 try/catch 上为工作目录和参数抛出异常?

WPF 分层数据模板

wpf - WPF ResourceDictionary 能否为每个请求返回一个新实例

.net - 在 ResourceDictionary 中使用 DataTrigger 定义样式,但在 View 中指定 DataTrigger 绑定(bind)路径

c# - Azure服务总线 "ReceiveAsync"

c# - linq的子查询方法不返回所有对象

c# - 取决于 UI 焦点状态的 WPF 命令路由行为不一致

wpf - 带百分比坐标的面板

c# - WPF/XAML 如何指定从中加载资源的程序集?