Xamarin.Forms 如何在多平台应用程序中使用分段控制

How to use Segmented Control in Multiplatform App in Xamarin.Forms

到目前为止,这是我尝试过的。我正在尝试加载它 programmatically.I 正在多平台项目中编写此代码。如附图所示。

我在这里。

var layout = new StackLayout()
{
    Orientation = StackOrientation.Vertical,
    Spacing = 20,
    Padding = new Thickness(0, 20, 0, 0)
};

if (Device.OS == TargetPlatform.iOS)
{
    var segmentControl = new UISegmentedControl();
    segmentControl.Frame = new CGRect(20, 20, 280, 40);
    segmentControl.InsertSegment("One", 0, false);
    segmentControl.InsertSegment("Two", 1, false);
    segmentControl.SelectedSegment = 1;
    segmentControl.ValueChanged += async (sender, e) =>
    {
        var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment;
        await MainPage.DisplayAlert($"Native Segmented Control Clicked {selectedSegmentId}",
                                                  "Whoa!!!!!!", "OK");
    };
    layout.Children.Add(segmentControl);
}

这样可以吗?或者自定义渲染是唯一的解决方案?

可以在使用 Xamarin.Forms 编写的 iOS 应用程序中使用 SegmentedControl。

如果您要使用 shared project approach with Xamarin.Forms,您所询问的代码将非常适合。

在这种情况下,您需要在条件指令 #if __IOS__ 中包装 iOS 特定代码(#if __ANDROID__ 用于 Android 特定代码)

var layout = new StackLayout()
{
    Orientation = StackOrientation.Vertical,
    Spacing = 20,
    Padding = new Thickness(0, 20, 0, 0)
};

#if __IOS__
if (Device.OS == TargetPlatform.iOS)
{
    var segmentControl = new UISegmentedControl();
    segmentControl.Frame = new CGRect(20, 20, 280, 40);
    segmentControl.InsertSegment("One", 0, false);
    segmentControl.InsertSegment("Two", 1, false);
    segmentControl.SelectedSegment = 1;
    segmentControl.ValueChanged += async (sender, e) =>
    {
        var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment;
        await MainPage.DisplayAlert($"Native Segmented Control Clicked {selectedSegmentId}",
                                                  "Whoa!!!!!!", "OK");
    };
    layout.Children.Add(segmentControl);
}
#endif

James Montemagno Embedding Native Controls into Xamarin.Forms

提供了一个很好的示例来展示如何将 UISegmentedControl 与 Xamarin.Forms 一起使用

但是,看起来你有基于PCL方法的解决方案。

使用时 Portable Class Library approach with Xamarin.Forms, you will have to create a custom control (check this simple example about UISegmentedControl) or use 3rd party controls like SegmentedControl.FormsPlugin