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

Imt*_*ath 2 c# resourcedictionary xamarin xamarin.forms

我正在创建一个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"];
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了此错误消息.

未找到密钥异常表示字典中不存在"greenButton".

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

Sus*_*ver 5

Resources.Add需要包含样式的基于文本的名称,以便按名称检索它:

Resources.Add ("greenButton", greenButton);
Run Code Online (Sandbox Code Playgroud)