【发布时间】:2016-12-07 16:33:14
【问题描述】:
所以我在绑定到 ObservableCollection 的 UWP 应用程序中创建 GridView。
XAML:
<Page.Resources>
<CollectionViewSource
x:Name="ListSource"
Source="{x:Bind model.ShowList}"
IsSourceGrouped="false"
/>
</Page.Resources>
...
<Page>
<GridView x:Name="lvListSource" ItemsSource="{Binding Source={StaticResource ListSource}}" SelectedIndex="-1" Grid.Row="2" HorizontalContentAlignment="Center" SelectionChanged="lvEpisodeListSource_SelectionChanged">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:PageInput">
<TextBlock Name="AlbumBlock" Foreground="Black" FontWeight="Normal" FontSize="15" Margin="5,0,5,0"
Text="{x:Bind Name}" HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</page>
C#:
public MainCategoryModel model;
public MainPage()
{
model = new MainCategoryModel();
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//initialize model data in code and stuff comes out correctly
//model.Clear() give unknown error here
model.Add(new PageInput() {...});
lvListSource.ItemsSource = model.myList;
}
public class MainCategoryModel
{
public ObservableCollection<PageInput> myList { get; set; }
public MainCategoryModel()
{
myList = new ObservableCollection<PageInput>();
}
public void AddShow(PageInput show)
{
myList.Insert(0, show);
}
public void Clear()
{
myList.Clear();
}
}
当我只向集合中添加项目时,ObservableCollection 正确初始化并且页面加载非常好。问题是,我想在每次调用 OnNavigatedTo 函数时更新 GridView 绑定的 ObservableCollection。这包括从集合中删除项目。每次我删除项目或尝试清除 ObservableCollection 时,页面都无法加载并出现未知错误。有没有办法从已绑定的 Observable Collection 中修改和删除值?
作为一个附带问题,如果我没有在 OnNavigatedTo 的末尾重新设置 ItemsSource 属性,则在向 Collection 添加值后会立即调用 SelectionChanged 事件,因为它是在 XAML 中设置的。有没有办法在将项目添加到 GridView 时不调用 SelectionChanged 事件?
【问题讨论】: