Imt*_*ath 6 c# xaml xamarin xamarin.forms
我正在使用Xamarin.Forms应用程序。我在App.xaml中定义的以下样式
<Application.Resources>
<ResourceDictionary>
<Style x:Key="blueButton" TargetType="Button">
<Setter Property="BackgroundColor"
Value="Blue" />
<Setter Property="TextColor"
Value="White" />
</Style>
</ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)
当我想使用MainPage.xaml中的样式时,它工作得很好。
<Button x:Name="CreateGridButton"
Margin="0,15,0,0"
Clicked="CreateGridButton_Clicked"
Text="Create Grid Layout" Style="{StaticResource blueButton}" />
Run Code Online (Sandbox Code Playgroud)
但是,当我要从MainPage.xaml.cs执行相同操作时,它显示错误消息“当前上下文中不存在名称'blueButton'”。
Button createSL = new Button();
createSL.Text = "Create Stack Layout";
createSL.Style = (Style)Resources["blueButton"];
Run Code Online (Sandbox Code Playgroud)
我也尝试了以下方法,也显示了相同的错误。
createSL.Style = bluebutton;
Run Code Online (Sandbox Code Playgroud)
根据我的要求,我无法在XAML中创建此按钮。因此,请从后面的代码中帮助我。
由于您在 App.xaml 中定义了您的样式:
createSL.Style = (Style)Application.Current.Resources["blueButton"];
Run Code Online (Sandbox Code Playgroud)
请尝试这样做
在您的 App 构造函数中创建样式并将其添加到资源中,如下所示:
public App ()
{
var buttonStyle = new Style (typeof(Button)) {
Setters = {
...
new Setter { Property = Button.TextColorProperty, Value = Color.Teal }
}
};
Resources = new ResourceDictionary ();
Resources.Add ("blueButton", buttonStyle);
...
}
Run Code Online (Sandbox Code Playgroud)
之后使用此样式并设置为这样的按钮:
Button createSL = new Button();
createSL.Text = "Create Stack Layout";
createSL.Style = (Style)Application.Current.Resources ["blueButton"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1705 次 |
| 最近记录: |