在资源字典异常中找不到密钥 - Xamarin.Forms

Key is not found in resource dictionary Exception - 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"];

上面的代码给出了这个error message。

A Key not found Exception stating that 'greenButton' is not present in the dictionary.

但是我已经完成了 Xamarin.Forms 文档中提到的所有操作。请帮我解决它!

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

Resources.Add ("greenButton", greenButton);