我想在用户更改页面时从flipview中删除项目。有什么我能做的吗?

时间:2016-07-12 10:16:34

标签: c# uwp flipview

我的要求是我在我的应用程序中使用了flipview并动态添加页面。我想在我点击addpages按钮时执行此操作,当前页面从flipview中移除并且新页面出现。我的addpage代码

   public void Add_Pages_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            my_canvas = new Canvas();
            my_canvas.Name = "Item" + DateTime.Now.ToFileTime().ToString();
            //fp1.ItemsSource = fi;
            fp1.Items.Add(my_canvas);
            fp1.SelectionChanged += Fp1_SelectionChanged;
            Stickers1.Visibility = Visibility.Collapsed;
            Backgrounds1.Visibility = Visibility.Collapsed;
            Popup_wordart.IsOpen = false;
            PopUp_Media.IsOpen = false;
            my_canvas.Visibility = Visibility.Collapsed;
            Audio_Recorder.IsOpen = false;
        }
        catch (Exception ex)
        {


        }
       // Backward_Arrow.Visibility = Visibility.Visible;
    }

1 个答案:

答案 0 :(得分:0)

执行此工作的一种非常方便的方法是在DataTemplate中为FlipView的每个项目构建一个结构,然后使用ObservableCollection添加,删除,刷新项目FlipView

<FlipView x:Name="flipView" ItemsSource="{x:Bind flipviewCollection}">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <Canvas>
                <Image Source="{Binding ImageSource}" Stretch="None"/>
            </Canvas>
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>

DataTemplate

中需要绑定的数据定义模型
public class ImageSourceClass
{
    public string ImageSource { get; set; }
}

然后在FlipView后面的代码中,创建此数据模型的集合并将数据添加到此集合中:

ObservableCollection<ImageSourceClass> flipviewCollection = new ObservableCollection<ImageSourceClass>();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    flipviewCollection.Clear();
    flipviewCollection.Add(new ImageSourceClass { ImageSource = "Assets/1.jpg" });
    flipviewCollection.Add(new ImageSourceClass { ImageSource = "Assets/2.jpg" });
    flipviewCollection.Add(new ImageSourceClass { ImageSource = "Assets/3.jpg" });
    flipviewCollection.Add(new ImageSourceClass { ImageSource = "Assets/4.jpg" });
    flipviewCollection.Add(new ImageSourceClass { ImageSource = "Assets/5.jpg" });
}

最后,如果你想删除一个项目并在按钮点击事件中添加一个新项目:

private void Button_Click(object sender, RoutedEventArgs e)
{
    //index = flipView.SelectedIndex + 1 because when remove one item, next item will be shown, 
    //it will behavior like a new item replace the old one.
    flipviewCollection.Insert(flipView.SelectedIndex + 1, new ImageSourceClass { ImageSource = "Assets/new.jpg" });
    flipviewCollection.Remove(flipView.SelectedItem as ImageSourceClass);                                
}

问题是,如果您没有使用此方法构建FlipView,您只需手动将项目添加到FlipView,您还需要像在代码中一样删除一个项目,例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var my_canvas = new Canvas();
    var textbox = new TextBox();
    my_canvas.Children.Add(textbox);
    flipView.Items.Insert(flipView.SelectedIndex + 1, my_canvas);
    flipView.Items.RemoveAt(flipView.SelectedIndex);              
}