1
0
Fork 0
mirror of https://github.com/Nioux/AideDeJeu.git synced 2025-10-29 14:35:45 +00:00

Refactor / binding

This commit is contained in:
Yan Maniez 2019-10-14 14:53:18 +02:00
parent b151e42240
commit d0701dc686
6 changed files with 238 additions and 264 deletions

View file

@ -0,0 +1,51 @@
using Xamarin.Forms;
namespace AideDeJeu.Tools
{
public class BindableToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty =
BindableProperty.Create("BindableToolbarItem", typeof(bool), typeof(ToolbarItem),
true, BindingMode.TwoWay, propertyChanged: OnIsVisibleChanged);
public BindableToolbarItem()
{
InitVisibility();
}
public bool IsVisible
{
get { return (bool)GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
private void InitVisibility()
{
OnIsVisibleChanged(this, false, IsVisible);
}
private static void OnIsVisibleChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var item = bindable as BindableToolbarItem;
if (item != null && item.Parent == null)
return;
if (item != null)
{
var items = ((Page)item.Parent)?.ToolbarItems;
if (Equals(items, null)) return;
if ((bool)newvalue && !items.Contains(item))
{
//Device.BeginInvokeOnMainThread(() => { items.Add(item); });
Device.BeginInvokeOnMainThread(() => { items.Insert(0, item); });
}
else if (!(bool)newvalue && items.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { items.Remove(item); });
}
}
}
}
}

View file

@ -226,5 +226,27 @@ namespace AideDeJeu.ViewModels
SetProperty(ref _CurrentItem, value);
}
}
private bool _FilterIsPresented = false;
public bool FilterIsPresented
{
get
{
return _FilterIsPresented;
}
set
{
SetProperty(ref _FilterIsPresented, value);
}
}
private Command _ChangeFilterIsPresentedCommand = null;
public Command ChangeFilterIsPresentedCommand
{
get
{
return _ChangeFilterIsPresentedCommand ?? (_ChangeFilterIsPresentedCommand = new Command(() => FilterIsPresented = !FilterIsPresented));
}
}
}
}

View file

@ -21,9 +21,10 @@
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolbarItems>
<ToolbarItem Name="AddToFavorites" Text="Ajouter aux favoris" Order="Primary" Icon="round_star.png" Command="{Binding Main.Navigator.AddToFavoritesCommand}" />
<ToolbarItem Name="Print" Text="Générer un PDF" Order="Primary" Icon="scroll_unfurled.png" Command="{Binding Main.Navigator.GeneratePDFCommand}" CommandParameter="{Binding Item.Markdown}" />
<ToolbarItem Name="Speak" Text="Écouter / Arrêter" Order="Primary" Icon="round_star.png" Command="{Binding Main.Speech.SpeakItemCommand}" CommandParameter="{Binding Item}" />
<tools:BindableToolbarItem Name="Filter" Text="Filtrer" Order="Primary" Icon="funnel.png" IsVisible="{Binding Filter, Converter={StaticResource NullToFalseConverter}, Mode=OneWay}" Command="{Binding Main.ChangeFilterIsPresentedCommand, Mode=OneTime}" />
<ToolbarItem Name="AddToFavorites" Text="Ajouter aux favoris" Order="Primary" Icon="round_star.png" Command="{Binding Main.Navigator.AddToFavoritesCommand, Mode=OneTime}" />
<ToolbarItem Name="Print" Text="Générer un PDF" Order="Secondary" Icon="scroll_unfurled.png" Command="{Binding Main.Navigator.GeneratePDFCommand, Mode=OneTime}" CommandParameter="{Binding Item.Markdown}" />
<ToolbarItem Name="Speak" Text="Écouter / Arrêter" Order="Secondary" Icon="scroll_unfurled.png" Command="{Binding Main.Speech.SpeakItemCommand, Mode=OneTime}" CommandParameter="{Binding Item}" />
</ContentPage.ToolbarItems>
<Grid>
<!--<ScrollView Orientation="Vertical" BackgroundColor="{StaticResource HDWhite}">
@ -36,9 +37,9 @@
<ListView Grid.Column="0" Grid.Row="0" x:Name="ItemsListView" ItemsSource="{Binding Children}" VerticalOptions="FillAndExpand" HasUnevenRows="true" CachingStrategy="RecycleElement" SelectedItem="{Binding SelectedItem}" ItemTapped="ItemsListView_ItemTapped">
<ListView.Header>
<mdview:MarkdownView
Theme="{StaticResource MonsterMarkdownTheme}"
Markdown="{Binding Item.Markdown}"
NavigateToLinkCommand="{Binding Main.Navigator.NavigateToLinkCommand}"
Theme="{StaticResource MonsterMarkdownTheme}"
Markdown="{Binding Item.Markdown}"
NavigateToLinkCommand="{Binding Main.Navigator.NavigateToLinkCommand}"
/>
</ListView.Header>
<ListView.ItemTemplate>

View file

@ -18,58 +18,33 @@ namespace AideDeJeu.Views.Library
{
[XamlCompilation(XamlCompilationOptions.Compile)]
[QueryProperty("Path", "path")]
public partial class ItemPage : ContentPage, INotifyPropertyChanged
public partial class ItemPage : ContentPage
{
//public MainViewModel Main
//{
// get
// {
// return DependencyService.Get<MainViewModel>();
// }
//}
//private ItemViewModel _Item = new ItemViewModel();
public ItemViewModel Item
{
get
{
return BindingContext as ItemViewModel;
//return _Item;
}
//set
//{
// SetProperty(ref _Item, value);
//}
}
public ItemPage()
{
//BindingContext = this;
InitializeComponent();
}
public ItemPage(string id)
{
//BindingContext = this;
InitializeComponent();
Path = id;
//LoadPageAsync();
}
public ItemPage(ItemViewModel itemViewModel)
{
//BindingContext = this;
InitializeComponent();
Path = itemViewModel.Item.Id;
//Item = itemViewModel;
}
//protected override void OnAppearing()
//{
// base.OnAppearing();
// LoadPageAsync();
//}
protected override void OnAppearing()
{
base.OnAppearing();
@ -98,60 +73,6 @@ namespace AideDeJeu.Views.Library
}
}
//private async Task LoadPageAsync()
//{
// if (Path == null) return;
// var regex = new Regex("/?(?<file>.*?)(_with_(?<with>.*))?\\.md(#(?<anchor>.*))?");
// var match = regex.Match(Uri.UnescapeDataString(Path));
// var file = match.Groups["file"].Value;
// var anchor = match.Groups["anchor"].Value;
// var with = match.Groups["with"].Value;
// Item item = null;
// try
// {
// Main.IsBusy = true;
// Main.IsLoading = true;
// item = await Task.Run(async () => await Main.Store.GetItemFromDataAsync(file, anchor));
// }
// finally
// {
// Main.IsBusy = false;
// Main.IsLoading = false;
// }
// if (item != null)
// {
// var items = item; // as Items;
// var filterViewModel = items.GetNewFilterViewModel();
// var itemsViewModel = new ItemViewModel() { Item = items, AllItems = items, Filter = filterViewModel };
// this.Item = itemsViewModel;
// itemsViewModel.LoadItemsCommand.Execute(null);
// if (!string.IsNullOrEmpty(with))
// {
// var swith = with.Split('_');
// for (int i = 0; i < swith.Length / 2; i++)
// {
// var key = swith[i * 2 + 0];
// var val = swith[i * 2 + 1];
// filterViewModel.FilterWith(key, val);
// }
// }
// //SwitchToMainTab();
// //if (filterViewModel == null)
// //{
// // await GotoItemsPageAsync(itemsViewModel);
// //}
// //else
// //{
// // await GotoFilteredItemsPageAsync(itemsViewModel);
// //}
// }
// else
// {
// //await App.Current.MainPage.DisplayAlert("Lien invalide", s, "OK");
// }
//}
private void ItemsListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item == null) return;
@ -161,32 +82,5 @@ namespace AideDeJeu.Views.Library
lv.SelectedItem = null;
}
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
CallOnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void CallOnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}

View file

@ -5,6 +5,8 @@
xmlns:pc="clr-namespace:AideDeJeu.Views.PlayerCharacter"
xmlns:library="clr-namespace:AideDeJeu.Views.Library"
xmlns:tools="clr-namespace:AideDeJeu.Tools"
xmlns:vm="clr-namespace:AideDeJeu.ViewModels"
xmlns:libvm="clr-namespace:AideDeJeu.ViewModels.Library"
x:Class="AideDeJeu.Views.MainShell"
BackgroundColor="{DynamicResource HDWhite}"
FlyoutBackgroundColor="{DynamicResource HDWhite}"
@ -12,7 +14,11 @@
Shell.TitleColor="{DynamicResource HDBlack}"
Shell.UnselectedColor="{DynamicResource HDLightGrey}"
FlyoutHeaderBehavior="Scroll"
>
FlyoutIsPresented="{Binding Main.FilterIsPresented, Mode=TwoWay}"
x:DataType="vm:BaseViewModel">
<Shell.BindingContext>
<vm:BaseViewModel />
</Shell.BindingContext>
<Shell.Resources>
<ResourceDictionary>
<tools:MonsterMarkdownTheme x:Key="MonsterMarkdownTheme" />
@ -47,7 +53,7 @@
<StackLayout>-->
<StackLayout BindableLayout.ItemsSource="{Binding Main.CurrentItem.Filter.Filters}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<DataTemplate x:DataType="libvm:Filter">
<StackLayout Margin="10,5,10,0" Padding="0" Spacing="0">
<Label BindingContext="{Binding}" Text="{Binding Name}" Style="{StaticResource Key=heading4}" />
<Picker HorizontalOptions="FillAndExpand" ItemsSource="{Binding KeyValues, Mode=OneWay}" ItemDisplayBinding="{Binding Value, Mode=OneWay}" SelectedIndex="{Binding Index, Mode=TwoWay}" />

View file

@ -14,177 +14,177 @@ using Xamarin.Forms.Xaml;
namespace AideDeJeu.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainShell : Shell, INotifyPropertyChanged
public partial class MainShell : Shell
{
public MainShell()
{
InitializeComponent();
BindingContext = this;
//BindingContext = this;
}
public MainViewModel Main
{
get
{
return DependencyService.Get<MainViewModel>();
}
}
//public MainViewModel Main
//{
// get
// {
// return DependencyService.Get<MainViewModel>();
// }
//}
public ICommand NavigateToItemCommand
{
get
{
return new Command<string>(async (path) => await ExecuteNavigateToItemCommandAsync(path));
}
}
private async Task ExecuteNavigateToItemCommandAsync(string path)
{
await Navigation.PushAsync(new Library.ItemPage(path), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToItemCommand
//{
// get
// {
// return new Command<string>(async (path) => await ExecuteNavigateToItemCommandAsync(path));
// }
//}
//private async Task ExecuteNavigateToItemCommandAsync(string path)
//{
// await Navigation.PushAsync(new Library.ItemPage(path), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToHomeCommand
{
get
{
return new Command(async() => await ExecuteNavigateToHomeCommandAsync());
}
}
private async Task ExecuteNavigateToHomeCommandAsync()
{
await Navigation.PushAsync(new MainPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToHomeCommand
//{
// get
// {
// return new Command(async() => await ExecuteNavigateToHomeCommandAsync());
// }
//}
//private async Task ExecuteNavigateToHomeCommandAsync()
//{
// await Navigation.PushAsync(new MainPage(), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToPCCommand
{
get
{
return new Command(async () => await ExecuteNavigateToPCCommandAsync());
}
}
private async Task ExecuteNavigateToPCCommandAsync()
{
await Navigation.PushAsync(new PlayerCharacter.PlayerCharacterEditorPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToPCCommand
//{
// get
// {
// return new Command(async () => await ExecuteNavigateToPCCommandAsync());
// }
//}
//private async Task ExecuteNavigateToPCCommandAsync()
//{
// await Navigation.PushAsync(new PlayerCharacter.PlayerCharacterEditorPage(), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToDicesCommand
{
get
{
return new Command(async () => await ExecuteNavigateToDicesCommandAsync());
}
}
private async Task ExecuteNavigateToDicesCommandAsync()
{
await Navigation.PushAsync(new DicesPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToDicesCommand
//{
// get
// {
// return new Command(async () => await ExecuteNavigateToDicesCommandAsync());
// }
//}
//private async Task ExecuteNavigateToDicesCommandAsync()
//{
// await Navigation.PushAsync(new DicesPage(), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToBookmarksCommand
{
get
{
return new Command(async () => await ExecuteNavigateToBookmarksCommandAsync());
}
}
private async Task ExecuteNavigateToBookmarksCommandAsync()
{
await Navigation.PushAsync(new Library.BookmarksPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToBookmarksCommand
//{
// get
// {
// return new Command(async () => await ExecuteNavigateToBookmarksCommandAsync());
// }
//}
//private async Task ExecuteNavigateToBookmarksCommandAsync()
//{
// await Navigation.PushAsync(new Library.BookmarksPage(), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToDeepSearchCommand
{
get
{
return new Command(async () => await ExecuteNavigateToDeepSearchCommandAsync());
}
}
private async Task ExecuteNavigateToDeepSearchCommandAsync()
{
await Navigation.PushAsync(new Library.DeepSearchPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToDeepSearchCommand
//{
// get
// {
// return new Command(async () => await ExecuteNavigateToDeepSearchCommandAsync());
// }
//}
//private async Task ExecuteNavigateToDeepSearchCommandAsync()
//{
// await Navigation.PushAsync(new Library.DeepSearchPage(), true);
// this.FlyoutIsPresented = false;
//}
public ICommand NavigateToAboutCommand
{
get
{
return new Command(async () => await ExecuteNavigateToAboutCommandAsync());
}
}
private async Task ExecuteNavigateToAboutCommandAsync()
{
await Navigation.PushAsync(new AboutPage(), true);
this.FlyoutIsPresented = false;
}
//public ICommand NavigateToAboutCommand
//{
// get
// {
// return new Command(async () => await ExecuteNavigateToAboutCommandAsync());
// }
//}
//private async Task ExecuteNavigateToAboutCommandAsync()
//{
// await Navigation.PushAsync(new AboutPage(), true);
// this.FlyoutIsPresented = false;
//}
private string _HeaderTitle = string.Empty;
public string HeaderTitle
{
get
{
return _HeaderTitle;
}
set
{
SetProperty(ref _HeaderTitle, value);
}
}
protected override void OnNavigated(ShellNavigatedEventArgs args)
{
base.OnNavigated(args);
Debug.WriteLine(this.CurrentItem?.CurrentItem?.CurrentItem);
HeaderTitle = this.CurrentItem?.CurrentItem?.CurrentItem?.Route;
var content = this.CurrentItem?.CurrentItem?.CurrentItem?.Content;
Debug.WriteLine(content);
//private string _HeaderTitle = string.Empty;
//public string HeaderTitle
//{
// get
// {
// return _HeaderTitle;
// }
// set
// {
// SetProperty(ref _HeaderTitle, value);
// }
//}
//protected override void OnNavigated(ShellNavigatedEventArgs args)
//{
// base.OnNavigated(args);
// Debug.WriteLine(this.CurrentItem?.CurrentItem?.CurrentItem);
// HeaderTitle = this.CurrentItem?.CurrentItem?.CurrentItem?.Route;
// var content = this.CurrentItem?.CurrentItem?.CurrentItem?.Content;
// Debug.WriteLine(content);
this.CurrentItem.CurrentItem.CurrentItem.PropertyChanged += CurrentItem_PropertyChanged;
this.CurrentItem.CurrentItem.CurrentItem.Appearing += CurrentItem_Appearing;
this.CurrentItem.CurrentItem.CurrentItem.BindingContextChanged += CurrentItem_BindingContextChanged;
}
// this.CurrentItem.CurrentItem.CurrentItem.PropertyChanged += CurrentItem_PropertyChanged;
// this.CurrentItem.CurrentItem.CurrentItem.Appearing += CurrentItem_Appearing;
// this.CurrentItem.CurrentItem.CurrentItem.BindingContextChanged += CurrentItem_BindingContextChanged;
//}
private void CurrentItem_BindingContextChanged(object sender, EventArgs e)
{
Debug.WriteLine(e.ToString());
}
//private void CurrentItem_BindingContextChanged(object sender, EventArgs e)
//{
// Debug.WriteLine(e.ToString());
//}
private void CurrentItem_Appearing(object sender, EventArgs e)
{
Debug.WriteLine(e.ToString());
}
//private void CurrentItem_Appearing(object sender, EventArgs e)
//{
// Debug.WriteLine(e.ToString());
//}
private void CurrentItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Debug.WriteLine(e.PropertyName);
}
//private void CurrentItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
//{
// Debug.WriteLine(e.PropertyName);
//}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
//protected bool SetProperty<T>(ref T backingStore, T value,
// [CallerMemberName]string propertyName = "",
// Action onChanged = null)
//{
// if (EqualityComparer<T>.Default.Equals(backingStore, value))
// return false;
backingStore = value;
onChanged?.Invoke();
CallOnPropertyChanged(propertyName);
return true;
}
// backingStore = value;
// onChanged?.Invoke();
// CallOnPropertyChanged(propertyName);
// return true;
//}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void CallOnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
//#region INotifyPropertyChanged
//public event PropertyChangedEventHandler PropertyChanged;
//protected void CallOnPropertyChanged([CallerMemberName] string propertyName = "")
//{
// var changed = PropertyChanged;
// if (changed == null)
// return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
// changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
//}
//#endregion
}
}