Để tạo một phong cách trong C# xin vui lòng xem link to a xamarin developer guide for global styles này.
Ví dụ về mã C#: (thiết lập một từ điển tài nguyên trong lớp ứng dụng của bạn)
public class App : Application
{
public App()
{
var buttonStyle = new Style (typeof(Button)) {
Setters = {
...
new Setter { Property = Button.TextColorProperty, Value = Color.Teal }
new Setter { Property = Button.BackgroundColor, Value = Color.White }
// add more setters for the properties that you want to set here
}
};
// add this style into your resource dictionary.
Resources = new ResourceDictionary();
Resources.Add ("buttonStyle", buttonStyle);
...
}
...
}
Bạn có thể tạo điều khiển với những phong cách trong lớp học C# của bạn:
public class ApplicationStylesPageCS : ContentPage
{
public ApplicationStylesPageCS()
{
...
Content = new StackLayout {
Children = {
new Button { Text = "These buttons", Style = (Style)Application.Current.Resources ["buttonStyle"] },
new Button { Text = "are demonstrating", Style = (Style)Application.Current.Resources ["buttonStyle"] },
new Button { Text = "application styles", Style = (Style)Application.Current.Resources ["buttonStyle"]
}
}
};
}
}
Hoặc cách khác truy cập nó trong xaml như một tài nguyên tĩnh:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.ApplicationStylesPage" Title="Application" Icon="xaml.png">
<ContentPage.Content>
<StackLayout Padding="0,20,0,0">
<Button Text="These buttons" Style="{StaticResource buttonStyle}" />
<Button Text="are demonstrating" Style="{StaticResource buttonStyle}" />
<Button Text="application style overrides" Style="{StaticResource buttonStyle}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
Cảm ơn Chúa Giêsu, đề xuất của bạn trông thú vị. Tôi upvoted nhưng chưa bấm vào chấp nhận. Tôi có thể tạo tài nguyên này trong C# không? – Alan2
Vâng, bạn có thể tạo điều này trong C#, hãy nhớ rằng XAML chỉ là cú pháp đường trên mã C#. –
@Alan bạn có thể sử dụng mã thay thế :). Tôi đã cập nhật câu trả lời của mình –