【问题标题】:Using XAML style on CodeBehind在 CodeBehind 上使用 XAML 样式
【发布时间】:2014-08-15 04:34:31
【问题描述】:

我正在尝试在我的代码中使用 Style.xaml 中的样式 在我的风格上,我有这样的代码

文件 Style.xaml

<SolidColorBrush x:Key="FontGrey" Color="#FFC5C0C0"></SolidColorBrush>  

在我的 Apptest.xaml.cs 文件中,我有这样的代码

txt.Foreground =  new SolidColorBrush(Color.FromArgb(255, 252, 147, 25));

如果我想根据 style.xaml 更改前景色 我怎样才能做到这一点?我正在尝试使用资源,但它不起作用

注意:Style.xaml 和 Apptest.xaml 是分开的

【问题讨论】:

    标签: c# silverlight xaml windows-phone-8


    【解决方案1】:

    您可以在 Silverlight 中使用以下语法访问您定义的资源:

    txt.Foreground = (SolidColorBrush)Application.Current.Resources["FontGrey"];
    

    【讨论】:

      【解决方案2】:

      您可以像这样将您的样式放入 Apptest.xaml 中的 Window.Resources 中:

          <ResourceDictionary >
              <ResourceDictionary.MergedDictionaries>
                  <ResourceDictionary 
                    Source="Style1.xaml">
                  </ResourceDictionary>
              </ResourceDictionary.MergedDictionaries>
          </ResourceDictionary>
      

      然后在文件 Apptest.xaml.cs 后面的窗口代码中,您可以访问资源:

          InitializeComponent();
          txt.Foreground = Resources["FontGrey"] as SolidColorBrush;
      

      【讨论】:

      • 感谢您的关注,先生,我应该在哪里添加该代码?在 Apptest.xaml 或 Style.xaml 上?因为当我试图将该代码放在 Style.xaml 上时它不起作用。谢谢之前:))
      • Apptest.xaml.cs中你的window的代码后面的class,你可以把它放在调用InitializeComponent()之后,例如
      • 所以就像 this.initializeComponent();然后 ,因为我认为它的 xaml 语言,对不起,如果我不明白你的意思,因为我仍然是一个菜鸟,我想学习 :))
      • 当我尝试将该代码放入 page.resource 时,它​​要求关联的键(每个字典条目都必须有一个关联的键)。那么它是什么意思呢?
      • Page.Resources 中除了 ResourceDictionary 之外还有其他资源吗?
      【解决方案3】:

      如果假设资源可用,那么此代码应该适合您:

      txt.Foreground = (Brush)FindResource("FontGrey");
      

      【讨论】:

      • 感谢您的关注,先生......但是在我的代码中找不到 FindResource 函数。
      • 检查您的使用情况,这里有一个关于该功能的 msdn reference
      • 我的意思是我的 FindResources 功能没有提供,当我输入 FindRes.. 它还没有提供,我如何解决这个问题?感谢您的关注先生
      • 此方法在 Silverlight 中不可用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2016-04-25
      • 1970-01-01
      相关资源
      最近更新 更多