【问题标题】:Update ObservableCollection from another page/window in UWP从 UWP 中的另一个页面/窗口更新 ObservableCollection
【发布时间】:2017-01-12 13:37:49
【问题描述】:

在了解了 UWP 中的 ObservableCollection 之后,我立即尝试了一下,在 1 页中工作非常简单。但是,当我尝试在一个页面中显示 gridview 绑定到 ObservableCollection,并从另一个页面调用 Add data to that ObservableCollection 时,我遇到了错误。我不知道我的搜索技能是否仍然太低或者什么,但是在搜索了 30m 之后我没有找到解决方案。希望这里有一些指导。这是我的代码:

MainPage.xaml

<Grid.RowDefinitions>
        <RowDefinition Height="50*"></RowDefinition>
        <RowDefinition Height="400*"></RowDefinition>
    </Grid.RowDefinitions>
    <Button x:Name="btnNewWindow" Content="Show add window" FontSize="20" Grid.Row="0" Click="btnNewWindow_Click"></Button>
    <ListView x:Name="listView" Grid.Row="1">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="data:Test" x:Name="templateGrid">
                <StackPanel x:Name="stackPanel"  Orientation="Vertical" HorizontalAlignment="Center">
                    <TextBlock FontSize="18" Text="{x:Bind id}" HorizontalAlignment="Center"></TextBlock>
                    <TextBlock FontSize="10" Text="{x:Bind name}" HorizontalAlignment="Center"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

MainPage.xaml.cs

SQLite.Net.SQLiteConnection conn;
    private List<Test> tempList;
    public static ObservableCollection<Test> testList;
    public static string _bookID = "";
    private string bookTitle = "";

    public MainPage()
    {
        this.InitializeComponent();
        string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "testDB.db");
        conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
        conn.CreateTable<Test>();
        tempList = conn.Query<Test>(@"select * from Test");
        testList = new ObservableCollection<Test>(tempList);
        listView.ItemsSource = testList;
    }

    async private void btnNewWindow_Click(object sender, RoutedEventArgs e)
    {
        CoreApplicationView newView = CoreApplication.CreateNewView();
        int view_id = 0;

        await newView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            Frame frame = new Frame();
            frame.Navigate(typeof(AddPage), null);
            Window.Current.Content = frame;
            Window.Current.Activate();

            view_id = ApplicationView.GetForCurrentView().Id;

            var app_view = ApplicationView.GetForCurrentView();
            app_view.SetPreferredMinSize(new Size(500, 400));

            ApplicationView.PreferredLaunchWindowingMode = Windows.UI.ViewManagement.ApplicationViewWindowingMode.PreferredLaunchViewSize;
            ApplicationView.PreferredLaunchViewSize = new Size(500, 400);
            app_view.Title = $"Add page";
        });

        await ApplicationViewSwitcher.TryShowAsStandaloneAsync(view_id);
    }

AddPage.xaml

<Grid.RowDefinitions>
        <RowDefinition Height="70*"></RowDefinition>
        <RowDefinition Height="70*"></RowDefinition>
        <RowDefinition Height="70*"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox x:Name="txtID" Header="ID" Margin="20" Grid.Row="0"></TextBox>
    <TextBox x:Name="txtName" Header="Name" Margin="20" Grid.Row="1"></TextBox>
    <Button x:Name="btnAdd" Margin="20" Grid.Row="2" Content="Add" Click="btnAdd_Click"></Button>

AddPage.xaml.cs

SQLite.Net.SQLiteConnection conn;
    public AddPage()
    {
        this.InitializeComponent();
        string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "testDB.db");
        conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        string id = txtID.Text;
        string name = txtName.Text;
        MainPage.testList.Add(new App2.Test{ id = id, name = name });//Error here
        conn.Execute(@"insert into Test values (?,?)", id, name);
        Window.Current.Close();
    }

测试类:

public class Test
{
        public string id { get; set; }
        public string name { get; set; }

        public Test(){}
}

错误:

“System.InvalidCastException”类型的异常发生在 System.ObjectModel.dll 但未在用户代码中处理 附加信息:无法转换类型为“System.Collections.Specialized.NotifyCollectionChangedEventHandler”的 COM 对象 类类型

提前致谢。如有重复请见谅。

【问题讨论】:

  • 我相信问题可能出在 btnAdd_Click 事件方法上。如果字符串 id 与 int view_id 相关,则可能只需要对其进行解析。即代替字符串 id = 0; int.TryParse(txtID.Text, out id)。如果这不能解决问题,您能否发布与 id 和 name 相关的 Test 类字段和属性?
  • @David Cardinale :在这里,我将测试类代码添加到问题中。对不起,我忘了。
  • 我相信问题出在这一行: tempList = conn.Query(@"select * from Test"); tempList 需要 类型。我将创建一个单独的方法来执行此查询并返回 List。不幸的是,我必须跑步,但我希望这会有所帮助。

标签: c# sqlite uwp


【解决方案1】:

我可以重现您的问题。我将使用我们的内部渠道进行举报。

作为临时解决方法,我们应该能够使用Popup 来替换新视图。我们也可以毫无例外地将项目插入ObservableCollection

例如:

XAML 代码:

<Popup Name="MyPopup">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="70*"></RowDefinition>
            <RowDefinition Height="70*"></RowDefinition>
            <RowDefinition Height="70*"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBox x:Name="txtID" Header="ID" Margin="20" Grid.Row="0"></TextBox>
        <TextBox x:Name="txtName" Header="Name" Margin="20" Grid.Row="1"></TextBox>
        <Button x:Name="btnAdd" Margin="20" Grid.Row="2" Content="Add" Click="btnAdd_Click"></Button>
    </Grid>
</Popup>

后面的代码:

private void btnNewWindow_Click(object sender, RoutedEventArgs e)
{
    MyPopup.IsOpen = true;
}

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    string id = txtID.Text;
    string name = txtName.Text;
    testList.Add(new App2.Test { id = id, name = name });
    conn.Execute(@"insert into Test values (?,?)", id, name);
    MyPopup.IsOpen = false;
}

【讨论】:

    【解决方案2】:

    我可以为您注意几点:

    如果您的问题不是跨线程,您能否说明此异常发生的地点和时间?例如在启动添加窗口或关闭时,以及哪一行代码。

    抱歉无法对此发表评论,缺乏声誉:/

    【讨论】:

    • 当我点击第二页的按钮添加时出现异常。在 AddPage.xaml.cs 中标记。这些线程和背景对我来说是新的,必须对此进行研究。
    • 啊,如果你没有收到编译时错误,我强烈怀疑它与跨线程有关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多