简体   繁体   English

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

[英]Key is not found in resource dictionary Exception - Xamarin.Forms

I'm creating a Xamarin.Forms app. 我正在创建一个Xamarin.Forms应用程序。 I'm unable to set the style from code behind. 我无法从后面的代码中设置样式。 The following code is inside the constructor of my page. 以下代码位于我的页面的构造函数中。

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"];

The above code gives this error message . 上面的代码给出了此错误消息

A Key not found Exception stating that 'greenButton' is not present in the dictionary. 找不到键异常,表明字典中不存在“ greenButton”。

But I've done everything as mentioned in the Xamarin.Forms documentation. 但是我已经完成了Xamarin.Forms文档中提到的所有操作。 Kindly help me fix it! 请帮助我修复它!

Your Resources.Add needs to include the text-based name of the style in order to retrieve it by name: 您的Resources.Add需要包含样式的基于文本的名称,以便按名称进行检索:

ie

Resources.Add ("greenButton", greenButton);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM