2017-08-23 10 views
0

私は2つの異なるXAMLページを持っています。最初のページにはボタンがあり、他のページにはリストビューがあります。私はすでにいくつかのバインディングをして、 "Model"クラスを作成しています。
これは私のリストビューです:別のページでボタンをクリックしてListViewを更新するにはどうすればよいですか?

<ListView x:Name="ListaEventos" ItemsSource="{x:Bind Eventos}" FontFamily="Segoe UI Emoji"> 
       <ListView.ItemTemplate> 
        <DataTemplate x:DataType="data:Evento"> 
         <StackPanel Orientation="Horizontal"> 
          <TextBlock Text="{x:Bind Minuto}" Style="{ThemeResource CaptionTextBlockStyle}" VerticalAlignment="Center"/> 
          <TextBlock Text="{x:Bind Segundo}" Style="{ThemeResource CaptionTextBlockStyle}" VerticalAlignment="Center"/> 
          <TextBlock Text="{x:Bind Icono}" Margin="10,0,0,0" VerticalAlignment="Center"/> 
          <TextBlock Text="{x:Bind Accion}" Margin="10,0,0,0" VerticalAlignment="Center"/> 
          <TextBlock Text="{x:Bind Equipo}" VerticalAlignment="Center"/> 
         </StackPanel> 
        </DataTemplate> 
       </ListView.ItemTemplate> 
      </ListView> 

そして、これは私のモデルクラスです:最後に

public class Evento 
{ 
    public string Minuto { get; set; } 

    public string Segundo { get; set; } 

    public string Icono { get; set; } 

    public string Accion { get; set; } 

    public string Equipo { get; set; } 

} 

、私は他のページでボタンをしたと私はアイテムを追加したい、このような何か:

Eventos.Add(new Evento { Minuto = "10", Segundo = "00", Icono = "", Accion="Triple de", Equipo=" Visitante" }); 

私は多くの研究を行ってきましたが、有用な情報やそれに類するものが見つかりませんでした。お願いします、私はあなたの助けが必要です、ありがとう!

答えて

1

スタティックObservableCollectionを定義して、新しいアイテムを他のページに追加することができます。 ListViewObservableCollectionにバインドすることはできません。OnNavigatedToイベントをオーバーライドし、ObservableCollectionEventosに設定することはできません。例えば

public static ObservableCollection<Evento> StaticEvento; 
public ObservableCollection<Evento> Eventos { get; set; } 
public MainPage() 
{ 
    this.InitializeComponent(); 
    if (StaticEvento == null) 
    { 
     StaticEvento = new ObservableCollection<Evento>(); 
     StaticEvento.Add(new Evento { Minuto = "20", Segundo = "00", Icono = "", Accion = "Triple de", Equipo = " Visitante" }); 
     Eventos = StaticEvento; 
    } 
} 
protected override void OnNavigatedTo(NavigationEventArgs e) 
{ 
    Eventos = StaticEvento; 
} 

別のページ:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    MainPage.StaticEvento.Add(new Evento { Minuto = "10", Segundo = "00", Icono = "", Accion = "Triple de", Equipo = " Visitante" }); 
    Frame rootFrame = Window.Current.Content as Frame; 
    rootFrame.GoBack(); 
} 
+0

それは私にこの例外「システムを投げるように、ボタンのページがリストビューページの前に表示されますので、これは私のために動作しません。 NullReferenceException: 'オブジェクト参照がオブジェクトのインスタンスに設定されていません。' –

+0

@PabloJiménezPascualListViewページを最初に読み込まないと、新しい項目を追加する前に静的な 'ObservableCollection'をインスタンス化できます。 –

+0

ありがとうございました。私は最終的にButtonのページで "StaticEvento"と宣言し、私の​​場合によく合うようにコードを少し変更しました。 –

関連する問題