【问题标题】:How do I access a control in a Resource Dictionary from its code behind?如何从其后面的代码访问资源字典中的控件?
【发布时间】:2014-12-12 18:44:15
【问题描述】:

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

【问题讨论】:

    标签: c# wpf resourcedictionary windowless


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 很棒的发现!快乐编码:)
    • 在同一分钟内提问和回答?在发布问题之前,您一定已经输入了答案。
    猜你喜欢
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多