以编程方式创建滑动视图



我正在尝试实现使用Mode=Execute滑动时执行动作的滑动视图。xaml中的代码可以正常工作:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="swipe.MainPage">
<StackLayout x:Name="hg">
<SwipeView Threshold="100">
<SwipeView.LeftItems>
<SwipeItems Mode="Execute">

<SwipeItem Text="Delete"
IconImageSource="delete.png"
BackgroundColor="LightPink"
Invoked="SwipeItem_Invoked"
/>
</SwipeItems>
</SwipeView.LeftItems>
<!-- Content -->
<Grid HeightRequest="60"
WidthRequest="300"
BackgroundColor="LightGray">
<Label Text="Swipe right"
HorizontalOptions="Center"
VerticalOptions="Center" />
</Grid>
</SwipeView>
</StackLayout>
</ContentPage>

xaml.cs

public MainPage()
{
InitializeComponent();
}
private void SwipeItem_Invoked(object sender, EventArgs e)
{
DisplayAlert("xj", "cc", "dd");
}

但是当我尝试以编程方式创建相同的滑动视图时,调用滑动项时的函数不起作用。下面是代码:

public MainPage()
{
InitializeComponent();
Grid grid = new Grid
{
HeightRequest = 60,
WidthRequest = 300,
BackgroundColor = Color.LightGray
};
grid.Children.Add(new Label
{
Text = "Swipe right",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
});
SwipeItem delete = new SwipeItem
{
Text = "Remove",
BackgroundColor = Color.Pink
};
SwipeItems items = new SwipeItems
{

Mode = SwipeMode.Execute
};
items.Add(delete);
SwipeView swipe = new SwipeView
{
Threshold = 80,
LeftItems = new SwipeItems(items),
Content = grid

};
delete.Invoked += SwipeItem_Invoked;
hg.Children.Add(swipe);
}
private void SwipeItem_Invoked(object sender, EventArgs e)
{
DisplayAlert("xj", "cc", "dd");
}

虽然我指定了要执行的模式,但为什么它不工作?我做错了什么?提前感谢

下面是我测试的完整代码:

MainPage.xaml

<StackLayout x:Name="hg">
</StackLayout>

MainPage.xaml.cs

public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
Grid grid = new Grid
{
HeightRequest = 60,
WidthRequest = 300,
BackgroundColor = Color.LightGray
};
grid.Children.Add(new Label
{
Text = "Swipe right",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
});
SwipeItem delete = new SwipeItem
{
Text = "Remove",
BackgroundColor = Color.Pink
};
SwipeItems items = new SwipeItems
{
Mode = SwipeMode.Execute
};
items.Add(delete);
SwipeView swipe = new SwipeView
{
Threshold = 80,
LeftItems = new SwipeItems(items),
Content = grid

};
delete.Invoked += SwipeItem_Invoked;
hg.Children.Add(swipe);
}
private void SwipeItem_Invoked(object sender, EventArgs e)
{
DisplayAlert("xj", "cc", "dd");
}
}

最新更新