且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将索引值绑定到ScrollView的ScrollToAsync属性中的元素参数-Xamarin表单

更新时间:2023-10-11 17:17:34

您可以使用自定义可绑定Index属性创建自定义ScrollView.

You can create a custom ScrollView with a custom bindable Index property.

public class CustomScrollView : ScrollView
{
    public static readonly BindableProperty IndexProperty = BindableProperty.Create (
        propertyName: nameof (Index),
        returnType: typeof (int),
        declaringType: typeof (CustomScrollView),
        defaultValue: 0,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanged: HandleIndexChanged
    );

    static void HandleIndexChanged (BindableObject bindable, object oldValue, object newValue)
    {
        var view = (CustomScrollView)bindable;
        view.Index = (int)newValue;

        // Call your view.ScrollToAsync here.
        // Depending on the structure of your XAML you could call
        // it using view.Content to go through the control tree.
        // Such as (view.Content as StackLayout).Children[newValue]
    }

    public int Index
    {
        get { return (int)GetValue (IndexProperty); }
        set { SetValue (IndexProperty, value); }
    }
}

然后,您可以通过在XAML页中将此部分添加到ContentPage声明中来引用此自定义ScrollView,而不是普通的自定义ScrollView:

You can then reference this custom ScrollView in your XAML page instead of the normal one by adding this part to your ContentPage declaration:

xmlns:custom="clr-namespace:[YourNamespace];assembly=[YourAssembly]"

并引用如下控件:

<custom:CustomScrollView Index="{Binding TIndex}" />