一個非常convenoent的方式來做好這項工作的代碼是建立在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
綁定:在你FlipView
後面的代碼
public class ImageSourceClass
{
public string ImageSource { get; set; }
}
然後,創建這個數據模型的數據收集和添加到此集合:
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
手動,您還需要去掉manully一個像你的代碼只是舉例這裏:
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);
}