在 Xamarin Forms 中添加按钮的最佳方法是什么?

man*_*sta 2 c# xaml xamarin xamarin.forms visual-studio-2017

所以我是 Xamarin Forms 的新手,我发现了两种添加按钮的方法:

1.在.xaml文件中声明按钮

 <!--  <Button Text="Click Me!"
      Clicked="OnButtonClicked" VerticalOptions="CenterAndExpand" />-->
Run Code Online (Sandbox Code Playgroud)

和 .xaml.cs 文件

 public void OnButtonClicked(object sender, EventArgs args)
     {
         count++;

         label.Text =
             String.Format("{0} click{1}!", count, count == 1 ? "" : "s");
Run Code Online (Sandbox Code Playgroud)
  1. 仅在 .xaml.cs 文件中声明按钮

    using System;
    using Xamarin.Forms;
    
    namespace FormsGallery
    {
        class ButtonDemoPage : ContentPage
        {
            Label label;
            int clickTotal = 0;
    
            public ButtonDemoPage()
            {
                Label header = new Label
                {
                    Text = "Button",
                    Font = Font.BoldSystemFontOfSize(50),
                    HorizontalOptions = LayoutOptions.Center
                };
    
                Button button = new Button
                {
                    Text = "Click Me!",
                    Font = Font.SystemFontOfSize(NamedSize.Large),
                    BorderWidth = 1,
                    HorizontalOptions = LayoutOptions.Center,
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };
                button.Clicked += OnButtonClicked;
    
                label = new Label
                {
                    Text = "0 button clicks",
                    Font = Font.SystemFontOfSize(NamedSize.Large),
                    HorizontalOptions = LayoutOptions.Center,
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };
    
                // Accomodate iPhone status bar.
                this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
    
                // Build the page.
                this.Content = new StackLayout
                {
                    Children = 
                    {
                        header,
                        button,
                        label
                    }
                };
            }
    
            void OnButtonClicked(object sender, EventArgs e)
            {
                clickTotal += 1;
                label.Text = String.Format("{0} button click{1}",
                                        clickTotal, clickTotal == 1 ? "" : "s");
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

但问题是:我想知道哪种方式更适合添加按钮并且不会有任何未来的代码问题。

谢谢!

Noo*_*uvo 6

其实他们是一样的。这取决于一个人的选择。

我更喜欢 XAML 而非代码,因为

  • XAML 更清晰且易于理解。
  • XAML 似乎能够更好地尊重 UI 和控制器逻辑之间的“关注点分离”。
  • 它在 Visual Studio 中有智能感知

您可以在此处详细找到答案 https://developer.xamarin.com/guides/xamarin-forms/creating-mobile-apps-xamarin-forms/summaries/chapter07/