【问题标题】:How to change listview values in real time when the json file is modifiedjson文件修改时如何实时更改listview值
【发布时间】:2019-08-30 00:43:02
【问题描述】:

您希望json文件中的当前数据显示在列表视图中,而不会再次更新列表或丢失SelectedInex

我已经尝试了很多方法,但没有任何效果,它只有在您完全从 ItemsSource 更新列表视图时才有效,但如果我这样做,则 selectedIndex 会丢失

MainPage.Xaml

<Grid RequestedTheme="Light">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
             <RowDefinition Height="818*" />

        </Grid.RowDefinitions>
        <TextBox
            x:Name="titulo"
            Grid.Row="0"
            FontSize="40"
            PlaceholderText="Ingresa tu titulo"
            Text="{Binding SelectedItem.title, ElementName=listNotas}"
            TextChanged="Titulo_TextChanged" />

        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <ListView
                x:Name="listNotas"
                Width="450"
                Background="DimGray"
                SelectedItem="{Binding titulo.Text, Mode=TwoWay}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding title, Mode=TwoWay}" />
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <RichEditBox
                x:Name="editor"
                Width="760"
                HorizontalAlignment="Stretch" />
        </StackPanel>

MainPage.xaml.cs

 public ObservableCollection<Notes> mynotes = new ObservableCollection<Notes>();

        public string editpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Notas.json" );
        public MainPage()
        {
            this.InitializeComponent();

            // Load data of Notas.json to Listview
            using (StreamReader file = File.OpenText(editpath))
            {
                var json = file.ReadToEnd();
                baseNotes mainnotes = JsonConvert.DeserializeObject<baseNotes>(json);

                foreach (var item in mainnotes.notes)
                {
                    mynotes.Add(new Notes { title = item.title });
                }
                listNotas.ItemsSource = null;
                listNotas.ItemsSource = mynotes;
                listNotas.SelectedIndex = 0;
            } 
        }


        private void Titulo_TextChanged(object sender, TextChangedEventArgs e)
        { 
            // Saving textbox text to title value in json file
            string json = File.ReadAllText(editpath);
            dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            int indice = listNotas.SelectedIndex;
            jsonObj["notes"][indice]["title"] = titulo.Text;

            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
            File.WriteAllText(editpath, output);
            // Show json file text in RicheditBox
            editor.TextDocument.SetText(Windows.UI.Text.TextSetOptions.None, output);

        }

模型类:Notes.cs

public class Notes
    {
        public int created { get; set; }
       public string title { get; set; }


        public string text { get; set; }
        public int id { get; set; }
        public int updated { get; set; }
    }

    public class baseNotes
    {
        public List<Notes> notes { get; set; }
    }

json 示例:Notas.json

{
  "notes": [
    {
      "created": 4352346,
      "title": "but not refresh listview values",
      "text": "fdsgfgsd fsgf sgtryt",
      "id": 432542,
      "updated": 23524
    },
    {
      "created": 4352346,
      "title": "this new value",
      "text": "fdsgfgsd fsgf sgtryt",
      "id": 432542,
      "updated": 23524
    },
    {
      "created": 4352346,
      "title": "changing value",
      "text": "fdsgfgsd fsgf sgtryt",
      "id": 432542,
      "updated": 23524
    }
  ]
}

请不知道还能做什么,我已经用这个 2 天了,任何形式的帮助,无论多么微不足道,都会很棒

Aqui una imagen:

https://i.imgur.com/3619gg3.gif

正如您在文本框中写入时看到的那样,如果更改保存在 json 文件中,但如果您更新它,它们不会显示在列表视图中,但我希望在不更新的情况下显示更改

【问题讨论】:

  • 你有一个 ObservableCollection,到目前为止一切都很好,但没有任何东西会触发你的集合中的变化。我会考虑使用 FileSystemWatcher 和一些编码来在底层文件更改时更新您的集合
  • 这是我想要达到的目标i.imgur.com/cNWfGoo.gif
  • 我知道你想要什么,但你做错了两件事。 a) 您必须实现IPropertyChanged 并在Notes 类中更改磁贴时引发属性更改事件。 b) 您永远不会修改您的ObservableCollection&lt;Notes&gt; mynotes,而只是将其内容写入磁盘。话虽如此,我建议您检查其他答案,尤其是像 related, almost duplicated, one 这样的 MVVM 答案。

标签: c# json listview uwp uwp-xaml


【解决方案1】:

首先,你需要实现INotifyPropertyChanged并订阅PropertyChanged事件。此时title属性是可观察的。当你的title改变或UI文本改变时,它会收到更新通知。

public class Notes: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    public int created { get; set; }
    private string myTitle;
    public string title {
        get {
            return myTitle;
        }
        set {
            myTitle = value;
            OnPropertyChanged();
            }
        }


    public string text { get; set; }
    public int id { get; set; }
    public int updated { get; set; }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

那么,TextBox的Binding模式应该是TwoWay,UpdateSourceTrigger应该是PropertyChanged。这意味着如果你想在你输入的时候更新源,你需要将绑定的UpdateSourceTrigger设置为PropertyChanged。在这种情况下,当您在TextBox中输入时,它会通知它绑定的标题,并且listView中的textBlock也会更新。

.xaml:

<TextBox x:Name="titulo"
         Grid.Row="0"
         FontSize="40"
         PlaceholderText="Ingresa tu titulo"
         Text="{Binding SelectedItem.title, ElementName=listNotas,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
         TextChanged="Titulo_TextChanged" />

【讨论】:

  • 这几乎就是我在评论中所说的,以及为什么我将答案与您的类似解决方案联系起来
  • 谢谢,我可以将所有步骤应用于每个人,但它只适用于第一个元素Text="{x:Bind Mynotes[0].title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 我怎样才能让它像这样遍历整个数组:Text =" {x: Bind Mynotes [ListNotas.SeletedIndex] .title, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged} " 但它没有允许我,请是我唯一需要的东西
  • 我终于成功了,我跳过另一个问题在这里发布:stackoverflow.com/questions/57731893/…
猜你喜欢
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 2011-01-15
  • 2022-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多