滑动时如何动态添加FlipView项目(文本内容)?

时间:2019-06-08 14:22:14

标签: c# uwp flipview

我想在UWP中动态添加新的翻转视图项。这样我就可以在翻转视图中添加无限项。例如,要获取热门新闻并以翻转视图逐一显示。 我从互联网上找到了一些类似的代码,并对其做了一些修改。 下面是xaml代码和cs代码。 如您所见,我想使用FlipView_SelectionChanged()动态添加新的翻转视图项目,但是失败了。我希望添加新的 翻转文本内容为Name new 3Name new 4 ...

的视图项

有人可以帮忙吗?谢谢!

XAML:

<Grid Name="grid">
    <FlipView Name="flipView" ItemsSource="{Binding ModelItems}">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Name}" FontSize="60" />
                </StackPanel>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>
</Grid>

C#:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        flipView.SelectionChanged += FlipView_SelectionChanged;
    }

    private void FlipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Debug.WriteLine("flipview selection changed...index = " + flipView.SelectedIndex);

        BaseViewModel bv = new BaseViewModel();
        bv.ModelItems.Add(new BaseViewModelItem() { Name = "Name new " + flipView.SelectedIndex });

        //grid.DataContext = bv;

        Debug.WriteLine("flipview selection changed...count = " + bv.ModelItems.Count);
    }

    protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        grid.DataContext = new BaseViewModel();
    }

    public class BaseViewModelItem
    {
        public string Name { get; set; }
    }

    public class BaseViewModel
    {
        public ObservableCollection<BaseViewModelItem> ModelItems { get; set; }
        public BaseViewModel()
        {
            ModelItems = new ObservableCollection<BaseViewModelItem>();
            ModelItems.Add(new BaseViewModelItem() { Name = "Name 1" });
            ModelItems.Add(new BaseViewModelItem() { Name = "Name 2" });
            ModelItems.Add(new BaseViewModelItem() { Name = "Name 3" });
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这里有两件事在起作用。首先,您无需分配整个视图模型的新实例即可进行更改-只需检索现有视图模型并添加新项即可:

var vm = (BaseViewModel)grid.DataContext;
bv.ModelItems.Add(
    new BaseViewModelItem() { 
      Name = "Name new " + flipView.SelectedIndex 
    });

然后,附加事件的时间就会出现问题。如果您将其正确连接到构造函数中,则在首次设置DataContext并将项目添加到ObservableCollection时立即将其触发-并在此刻尝试添加项目将使您最终遭受灾难性的失败。相反,您应该仅在设置DataContext之后才附加事件-因此在设置数据上下文之后,将flipView.SelectionChanged += FlipView_SelectionChanged;从构造函数中删除OnNavigatedToprotected override void OnNavigatedTo(NavigationEventArgs e) { grid.DataContext = new BaseViewModel(); flipView.SelectionChanged += FlipView_SelectionChanged; } >

https://{id}.example.com/ -> https://{id}.execute-api.us-east-1.amazonaws.com/prod/

这样,在更改选择时将正确添加项目。

答案 1 :(得分:0)

我修改了您共享的代码。我建议您每当添加到ModelItems的项目更新它绑定的元素时,都使用数据绑定而不是FlipView_SelectionChanged()。我希望这会有所帮助。

<Grid Name="grid">
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Grid Grid.Row="0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Content="Add New FlipView Item" Click="Button_Click"/>
        <DockPanel Grid.Column="1">
            <TextBlock>Flipview Item Count : </TextBlock>
            <TextBlock Text="{Binding ModelItems.Count}"/>
        </DockPanel>
    </Grid>

    <FlipView Grid.Row="1" Name="flipView" ItemsSource="{Binding ModelItems,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <DockPanel>
                        <TextBlock Text="Index:" FontSize="20"/>
                        <TextBlock Text="{Binding Index}" FontSize="60" />
                    </DockPanel>
                    <DockPanel>
                        <TextBlock Text="Name:" FontSize="20"/>
                        <TextBlock Text="{Binding Name}" FontSize="60" />
                    </DockPanel>
                </StackPanel>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>
</Grid>

逻辑零件代码

//Interaction logic for MainWindow.xaml
public partial class MainWindow : Window
{
    public BaseViewModel ViewModel { get; set; } = new BaseViewModel();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = ViewModel;
    }

    static int k = 3;
    private void Button_Click(object sender, RoutedEventArgs e) //can also implement using ICommand instead of event
    {
        this.ViewModel.ModelItems.Add(new BaseModelItem { Index = k, Name = "Name" + ++k });
    }
}

//--------Model------------
public class NotifyPropertyChanged : System.ComponentModel.INotifyPropertyChanged
{
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyRaised(string propertyname)
    {
        PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyname));
    }
}

public class BaseModelItem : NotifyPropertyChanged
{
    string _name = string.Empty;
    public string Name
    {
        get { return _name; }
        set { _name = value; OnPropertyRaised("Name"); }
    }

    int _index = 0;
    public int Index
    {
        get { return _index; }
        set { _index = value; OnPropertyRaised("Index"); }
    }
}

//--------ViewModel------------
public class BaseViewModel:NotifyPropertyChanged
{
    System.Collections.ObjectModel.ObservableCollection<BaseModelItem> _modelItems = new System.Collections.ObjectModel.ObservableCollection<BaseModelItem>();
    public System.Collections.ObjectModel.ObservableCollection<BaseModelItem> ModelItems
    {
        get { return _modelItems; }
        set { _modelItems = value; OnPropertyRaised("ModelItems"); }
    }

    public BaseViewModel()
    {
        ModelItems = new System.Collections.ObjectModel.ObservableCollection<BaseModelItem>();
        ModelItems.Add(new BaseModelItem() { Name = "Name 1", Index = 0 });
        ModelItems.Add(new BaseModelItem() { Name = "Name 2", Index = 1 });
        ModelItems.Add(new BaseModelItem() { Name = "Name 3", Index = 2 });
    }
}