资源字典Exception - Xamarin.Forms中找不到密钥

时间:2018-02-06 05:01:35

标签: c# xamarin xamarin.forms resourcedictionary

我正在创建一个Xamarin.Forms应用。我无法从代码背后设置样式。以下代码位于我的页面的构造函数中。

Style greenButton = new Style(typeof(Button))
{
    Setters =
    {
        new Setter{Property = Button.BackgroundColorProperty, Value = Color.Green },
        new Setter{Property = Button.TextColorProperty, Value = Color.Red}
    }
};

Resources = new ResourceDictionary();
Resources.Add(greenButton);

Button createSL = new Button();
createSL.Text = "Create Stack Layout";
createSL.Style = (Style) Resources["greenButton"];

上面的代码给出了error message

  

未找到密钥异常说明'greenButton'不存在   在字典里。

但是我已经完成了Xamarin.Forms文档中提到的所有内容。请帮我解决一下!

1 个答案:

答案 0 :(得分:5)

您的Resources.Add需要包含样式的基于文本的名称才能按名称检索它:

Resources.Add ("greenButton", greenButton);