По сути, на одной странице содержимого есть список, и при нажатии кнопки пользователь переходит на новую страницу, где он может настроить новый элемент для списка. Когда нажата кнопка сохранения, элемент добавляется в наблюдаемую коллекцию, но представление списка на другой странице не обновляется, чтобы отразить новый элемент. Кто-нибудь может пролить свет на это?
Я должен упомянуть, что я использую шаблон MVVM. Обе XAML-страницы связаны с одной и той же моделью представления.
Это страница с представлением списка.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="habytnew.Views.HabytsPage"
Title="{Binding Title}"
x:Name="BrowseItemsPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Command= "{Binding AddHabytCommand}"/>
</ContentPage.ToolbarItems>
<StackLayout>
<ListView
ItemsSource="{Binding Habyts}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="false"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10">
<Label Text="{Binding Text}"
d:Text="{Binding .}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemTextStyle}"
FontSize="16"
/>
<Label Text="{Binding Description}"
d:Text="Item description"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13" />
<Button Text="Accomplished?"
Command="{Binding AccomplishedClicked}"
FontSize="13"
/>
<Label Text="{Binding DisplayCompleted}"
BindingContext="{Binding Source={x:Reference BrowseItemsPage}, Path=BindingContext}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
Это страница, на которой вы настраиваете добавляемый новый элемент.
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:behaviorsPack="clr-namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.BehaviorsPack"
mc:Ignorable="d"
x:Class="habytnew.Views.NewHabytPage"
Title="New Item">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Cancel" Command="{Binding CancelAddHabytCommand}"/>
<ToolbarItem Text="Save" Command="{Binding SaveHabytCommand}" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout Spacing="20" Padding="15" BackgroundColor="White">
<Label Text="Text" FontSize="Medium"/>
<Entry Text="{Binding _example.Text}" d:Text="Item name" FontSize="Small" />
<Label Text="Description" FontSize="Medium" />
<Editor Text="{Binding _example.Description}" d:Text="Item description" FontSize="Small" Margin="0" />
<Label Text="Choose your days" FontSize="Medium" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Image="{Binding MonImageSource}" Command="{Binding MonClickedCommand}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="0"/>
<Button Image="drawable/t.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="1"/>
<Button Image="drawable/w.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="2"/>
<Button Image="drawable/t.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="3"/>
<Button Image="drawable/f.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="4"/>
<Button Image="drawable/s.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="5"/>
<Button Image="drawable/s.png" Command="{Binding MonClicked}" BorderColor="Transparent" BackgroundColor="Transparent" Grid.Row="0" Grid.Column="6"/>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="Notify me?" FontSize="Medium" Grid.Row="0" Grid.Column="0" />
<Switch IsToggled="{Binding Toggled}" Grid.Row="0" Grid.Column="1">
<Switch.Behaviors>
<behaviorsPack:EventToCommandBehavior
EventName="Toggled"
Command="{Binding SwitchToggledCommand}" />
</Switch.Behaviors>
</Switch>
<TimePicker
Time="{Binding SelectedTime}"
Format="T"
IsVisible="{Binding IsVisible}"
Grid.Row="1"
Grid.Column="1"/>
</Grid>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Это весь код модели представления.
using habytnew.Model;
using habytnew.Views;
using MvvmHelpers;
using Plugin.LocalNotifications;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace habytnew.ViewModels
{
public class HabytsViewModel : BaseViewModel
{
public HabytsViewModel()
{
Routing.RegisterRoute("newhabytpage", typeof(NewHabytPage));
Device.StartTimer(TimeSpan.FromSeconds(1), OnTimerTick);
SwitchToggledCommand = new Command(SwitchToggled);
AddHabytCommand = new Command(async () => await AddHabyt());
CancelAddHabytCommand = new Command(async () => await CancelAddHabyt());
SaveHabytCommand = new Command(async () => await SaveHabyt());
MonClickedCommand = new Command(MonClicked);
//TueClickedCommand = new Command(TueClicked);
//WedClickedCommand = new Command(WedClicked);
//ThuClickedCommand = new Command(ThuClicked);
//FriClickedCommand = new Command(FriClicked);
//SatClickedCommand = new Command(SatClicked);
//SunClickedCommand = new Command(SunClicked);
Habyts = new ObservableCollection<HabytItem>();
_example = new HabytItem
{
Text = "Item name",
Description = "This is an item description."
};
Title = "Habyts";
Habyts.Add(_example);
IsVisible = false;
Toggled = false;
}
public Command AddHabytCommand { get; }
public Command CancelAddHabytCommand { get; }
public Command SaveHabytCommand { get; }
public Command SwitchToggledCommand { get; }
public Command MonClickedCommand { get; }
public Command TueClickedCommand { get; }
public Command WedClickedCommand { get; }
public Command ThuClickedCommand { get; }
public Command FriClickedCommand { get; }
public Command SatClickedCommand { get; }
public Command SunClickedCommand { get; }
public HabytItem ExampleItem;
private HabytItem _example;
public ObservableCollection<HabytItem> Habyts { get; }
DateTime triggertime;
TimeSpan selectedtime;
bool _mon = false;
bool _tue = false;
bool _wed = false;
bool _thu = false;
bool _fri = false;
bool _sat = false;
bool _sun = false;
bool toggled;
bool isvisible;
List<bool> daysSelected = new List<bool>();
string monimagesource;
public TimeSpan SelectedTime
{
get { return selectedtime; }
set {
SetProperty(ref selectedtime, value);
SetTriggerTime();
}
}
public bool Toggled
{
get { return toggled; }
set {
SetProperty(ref toggled, value);
}
}
public bool IsVisible
{
get { return isvisible; }
set {
SetProperty(ref isvisible, value);
}
}
public string MonImageSource
{
get { return monimagesource; }
set {
SetProperty(ref monimagesource, value);
}
}
private async Task AddHabyt()
{
await Shell.Current.GoToAsync("newhabytpage");
}
private async Task CancelAddHabyt()
{
await Shell.Current.Navigation.PopAsync();
}
bool OnTimerTick()
{
if (toggled && DateTime.Now >= triggertime)
{
toggled = false;
Application.Current.MainPage.DisplayAlert("Reminder!", "'" + ExampleItem.Text + "' needs to be completed!", "OK");
}
return true;
}
public void SwitchToggled()
{
IsVisible = !IsVisible;
SetTriggerTime();
}
public async Task SaveHabyt()
{
if (_mon)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_tue)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_wed)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_thu)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_fri)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_sat)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
if (_sun)
{
daysSelected.Add(true);
}
else
{
daysSelected.Add(false);
}
ExampleItem = new HabytItem
{
Text = "Item name",
Description = "This is an item description."
};
_example.Plan = daysSelected;
if (Toggled == true)
{
CrossLocalNotifications.Current.Show(_example.Text, _example.Description, 101, DateTime.Today + SelectedTime);
}
await Shell.Current.Navigation.PopAsync();
Habyts.Add(_example);
}
void SetTriggerTime()
{
//if (Toggled)
//{
triggertime = DateTime.Today + SelectedTime;
if (triggertime < DateTime.Now)
{
triggertime += TimeSpan.FromDays(1);
}
//}
}
private void MonClicked()
{
if (_mon)
{
_mon = !_mon;
MonImageSource = "@drawable/m.png";
}
else
{
_mon = !_mon;
MonImageSource = "@drawable/m_on.png";
}
}
//private void TueClicked()
//{
// if (_tue)
// {
// _tue = !_tue;
// TUE.ImageSource = "@drawable/t.png";
// }
// else
// {
// _tue = !_tue;
// TUE.ImageSource = "@drawable/t_on.png";
// }
//}
//private void WedClicked()
//{
// if (_wed)
// {
// _wed = !_wed;
// WED.ImageSource = "@drawable/w.png";
// }
// else
// {
// _wed = !_wed;
// WED.ImageSource = "@drawable/w_on.png";
// }
//}
//private void ThuClicked()
//{
// if (_thu)
// {
// _thu = !_thu;
// THU.ImageSource = "@drawable/t.png";
// }
// else
// {
// _thu = !_thu;
// THU.ImageSource = "@drawable/t_on.png";
// }
//}
//private void FriClicked()
//{
// if (_fri)
// {
// _fri = !_fri;
// FRI.ImageSource = "@drawable/f.png";
// }
// else
// {
// _fri = !_fri;
// FRI.ImageSource = "@drawable/f_on.png";
// }
//}
//private void SatClicked()
//{
// if (_sat)
// {
// _sat = !_sat;
// SAT.ImageSource = "@drawable/s.png";
// }
// else
// {
// _sat = !_sat;
// SAT.ImageSource = "@drawable/s_on.png";
// }
//}
//private void SunClicked()
//{
// if (_sun)
// {
// _sun = !_sun;
// SUN.ImageSource = "@drawable/s.png";
// }
// else
// {
// _sun = !_sun;
// SUN.ImageSource = "@drawable/s_on.png";
// }
//}
}
}
Пожалуйста, извините за комментарий и ужасные логические выражения, которые я пытаюсь кому-то помочь.