1
0
Fork 0
mirror of https://github.com/Nioux/AideDeJeu.git synced 2025-10-31 07:26:09 +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); 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> </ResourceDictionary>
</ContentPage.Resources> </ContentPage.Resources>
<ContentPage.ToolbarItems> <ContentPage.ToolbarItems>
<ToolbarItem Name="AddToFavorites" Text="Ajouter aux favoris" Order="Primary" Icon="round_star.png" Command="{Binding Main.Navigator.AddToFavoritesCommand}" /> <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="Print" Text="Générer un PDF" Order="Primary" Icon="scroll_unfurled.png" Command="{Binding Main.Navigator.GeneratePDFCommand}" CommandParameter="{Binding Item.Markdown}" /> <ToolbarItem Name="AddToFavorites" Text="Ajouter aux favoris" Order="Primary" Icon="round_star.png" Command="{Binding Main.Navigator.AddToFavoritesCommand, Mode=OneTime}" />
<ToolbarItem Name="Speak" Text="Écouter / Arrêter" Order="Primary" Icon="round_star.png" Command="{Binding Main.Speech.SpeakItemCommand}" CommandParameter="{Binding Item}" /> <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> </ContentPage.ToolbarItems>
<Grid> <Grid>
<!--<ScrollView Orientation="Vertical" BackgroundColor="{StaticResource HDWhite}"> <!--<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 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> <ListView.Header>
<mdview:MarkdownView <mdview:MarkdownView
Theme="{StaticResource MonsterMarkdownTheme}" Theme="{StaticResource MonsterMarkdownTheme}"
Markdown="{Binding Item.Markdown}" Markdown="{Binding Item.Markdown}"
NavigateToLinkCommand="{Binding Main.Navigator.NavigateToLinkCommand}" NavigateToLinkCommand="{Binding Main.Navigator.NavigateToLinkCommand}"
/> />
</ListView.Header> </ListView.Header>
<ListView.ItemTemplate> <ListView.ItemTemplate>

View file

@ -18,58 +18,33 @@ namespace AideDeJeu.Views.Library
{ {
[XamlCompilation(XamlCompilationOptions.Compile)] [XamlCompilation(XamlCompilationOptions.Compile)]
[QueryProperty("Path", "path")] [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 public ItemViewModel Item
{ {
get get
{ {
return BindingContext as ItemViewModel; return BindingContext as ItemViewModel;
//return _Item;
} }
//set
//{
// SetProperty(ref _Item, value);
//}
} }
public ItemPage() public ItemPage()
{ {
//BindingContext = this;
InitializeComponent(); InitializeComponent();
} }
public ItemPage(string id) public ItemPage(string id)
{ {
//BindingContext = this;
InitializeComponent(); InitializeComponent();
Path = id; Path = id;
//LoadPageAsync();
} }
public ItemPage(ItemViewModel itemViewModel) public ItemPage(ItemViewModel itemViewModel)
{ {
//BindingContext = this;
InitializeComponent(); InitializeComponent();
Path = itemViewModel.Item.Id; Path = itemViewModel.Item.Id;
//Item = itemViewModel;
} }
//protected override void OnAppearing()
//{
// base.OnAppearing();
// LoadPageAsync();
//}
protected override void OnAppearing() protected override void OnAppearing()
{ {
base.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) private void ItemsListView_ItemTapped(object sender, ItemTappedEventArgs e)
{ {
if (e.Item == null) return; if (e.Item == null) return;
@ -161,32 +82,5 @@ namespace AideDeJeu.Views.Library
lv.SelectedItem = null; 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:pc="clr-namespace:AideDeJeu.Views.PlayerCharacter"
xmlns:library="clr-namespace:AideDeJeu.Views.Library" xmlns:library="clr-namespace:AideDeJeu.Views.Library"
xmlns:tools="clr-namespace:AideDeJeu.Tools" xmlns:tools="clr-namespace:AideDeJeu.Tools"
xmlns:vm="clr-namespace:AideDeJeu.ViewModels"
xmlns:libvm="clr-namespace:AideDeJeu.ViewModels.Library"
x:Class="AideDeJeu.Views.MainShell" x:Class="AideDeJeu.Views.MainShell"
BackgroundColor="{DynamicResource HDWhite}" BackgroundColor="{DynamicResource HDWhite}"
FlyoutBackgroundColor="{DynamicResource HDWhite}" FlyoutBackgroundColor="{DynamicResource HDWhite}"
@ -12,7 +14,11 @@
Shell.TitleColor="{DynamicResource HDBlack}" Shell.TitleColor="{DynamicResource HDBlack}"
Shell.UnselectedColor="{DynamicResource HDLightGrey}" Shell.UnselectedColor="{DynamicResource HDLightGrey}"
FlyoutHeaderBehavior="Scroll" FlyoutHeaderBehavior="Scroll"
> FlyoutIsPresented="{Binding Main.FilterIsPresented, Mode=TwoWay}"
x:DataType="vm:BaseViewModel">
<Shell.BindingContext>
<vm:BaseViewModel />
</Shell.BindingContext>
<Shell.Resources> <Shell.Resources>
<ResourceDictionary> <ResourceDictionary>
<tools:MonsterMarkdownTheme x:Key="MonsterMarkdownTheme" /> <tools:MonsterMarkdownTheme x:Key="MonsterMarkdownTheme" />
@ -47,7 +53,7 @@
<StackLayout>--> <StackLayout>-->
<StackLayout BindableLayout.ItemsSource="{Binding Main.CurrentItem.Filter.Filters}"> <StackLayout BindableLayout.ItemsSource="{Binding Main.CurrentItem.Filter.Filters}">
<BindableLayout.ItemTemplate> <BindableLayout.ItemTemplate>
<DataTemplate> <DataTemplate x:DataType="libvm:Filter">
<StackLayout Margin="10,5,10,0" Padding="0" Spacing="0"> <StackLayout Margin="10,5,10,0" Padding="0" Spacing="0">
<Label BindingContext="{Binding}" Text="{Binding Name}" Style="{StaticResource Key=heading4}" /> <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}" /> <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 namespace AideDeJeu.Views
{ {
[XamlCompilation(XamlCompilationOptions.Compile)] [XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainShell : Shell, INotifyPropertyChanged public partial class MainShell : Shell
{ {
public MainShell() public MainShell()
{ {
InitializeComponent(); InitializeComponent();
BindingContext = this; //BindingContext = this;
} }
public MainViewModel Main //public MainViewModel Main
{ //{
get // get
{ // {
return DependencyService.Get<MainViewModel>(); // return DependencyService.Get<MainViewModel>();
} // }
} //}
public ICommand NavigateToItemCommand //public ICommand NavigateToItemCommand
{ //{
get // get
{ // {
return new Command<string>(async (path) => await ExecuteNavigateToItemCommandAsync(path)); // return new Command<string>(async (path) => await ExecuteNavigateToItemCommandAsync(path));
} // }
} //}
private async Task ExecuteNavigateToItemCommandAsync(string path) //private async Task ExecuteNavigateToItemCommandAsync(string path)
{ //{
await Navigation.PushAsync(new Library.ItemPage(path), true); // await Navigation.PushAsync(new Library.ItemPage(path), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToHomeCommand //public ICommand NavigateToHomeCommand
{ //{
get // get
{ // {
return new Command(async() => await ExecuteNavigateToHomeCommandAsync()); // return new Command(async() => await ExecuteNavigateToHomeCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToHomeCommandAsync() //private async Task ExecuteNavigateToHomeCommandAsync()
{ //{
await Navigation.PushAsync(new MainPage(), true); // await Navigation.PushAsync(new MainPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToPCCommand //public ICommand NavigateToPCCommand
{ //{
get // get
{ // {
return new Command(async () => await ExecuteNavigateToPCCommandAsync()); // return new Command(async () => await ExecuteNavigateToPCCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToPCCommandAsync() //private async Task ExecuteNavigateToPCCommandAsync()
{ //{
await Navigation.PushAsync(new PlayerCharacter.PlayerCharacterEditorPage(), true); // await Navigation.PushAsync(new PlayerCharacter.PlayerCharacterEditorPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToDicesCommand //public ICommand NavigateToDicesCommand
{ //{
get // get
{ // {
return new Command(async () => await ExecuteNavigateToDicesCommandAsync()); // return new Command(async () => await ExecuteNavigateToDicesCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToDicesCommandAsync() //private async Task ExecuteNavigateToDicesCommandAsync()
{ //{
await Navigation.PushAsync(new DicesPage(), true); // await Navigation.PushAsync(new DicesPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToBookmarksCommand //public ICommand NavigateToBookmarksCommand
{ //{
get // get
{ // {
return new Command(async () => await ExecuteNavigateToBookmarksCommandAsync()); // return new Command(async () => await ExecuteNavigateToBookmarksCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToBookmarksCommandAsync() //private async Task ExecuteNavigateToBookmarksCommandAsync()
{ //{
await Navigation.PushAsync(new Library.BookmarksPage(), true); // await Navigation.PushAsync(new Library.BookmarksPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToDeepSearchCommand //public ICommand NavigateToDeepSearchCommand
{ //{
get // get
{ // {
return new Command(async () => await ExecuteNavigateToDeepSearchCommandAsync()); // return new Command(async () => await ExecuteNavigateToDeepSearchCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToDeepSearchCommandAsync() //private async Task ExecuteNavigateToDeepSearchCommandAsync()
{ //{
await Navigation.PushAsync(new Library.DeepSearchPage(), true); // await Navigation.PushAsync(new Library.DeepSearchPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
public ICommand NavigateToAboutCommand //public ICommand NavigateToAboutCommand
{ //{
get // get
{ // {
return new Command(async () => await ExecuteNavigateToAboutCommandAsync()); // return new Command(async () => await ExecuteNavigateToAboutCommandAsync());
} // }
} //}
private async Task ExecuteNavigateToAboutCommandAsync() //private async Task ExecuteNavigateToAboutCommandAsync()
{ //{
await Navigation.PushAsync(new AboutPage(), true); // await Navigation.PushAsync(new AboutPage(), true);
this.FlyoutIsPresented = false; // this.FlyoutIsPresented = false;
} //}
private string _HeaderTitle = string.Empty; //private string _HeaderTitle = string.Empty;
public string HeaderTitle //public string HeaderTitle
{ //{
get // get
{ // {
return _HeaderTitle; // return _HeaderTitle;
} // }
set // set
{ // {
SetProperty(ref _HeaderTitle, value); // SetProperty(ref _HeaderTitle, value);
} // }
} //}
protected override void OnNavigated(ShellNavigatedEventArgs args) //protected override void OnNavigated(ShellNavigatedEventArgs args)
{ //{
base.OnNavigated(args); // base.OnNavigated(args);
Debug.WriteLine(this.CurrentItem?.CurrentItem?.CurrentItem); // Debug.WriteLine(this.CurrentItem?.CurrentItem?.CurrentItem);
HeaderTitle = this.CurrentItem?.CurrentItem?.CurrentItem?.Route; // HeaderTitle = this.CurrentItem?.CurrentItem?.CurrentItem?.Route;
var content = this.CurrentItem?.CurrentItem?.CurrentItem?.Content; // var content = this.CurrentItem?.CurrentItem?.CurrentItem?.Content;
Debug.WriteLine(content); // Debug.WriteLine(content);
this.CurrentItem.CurrentItem.CurrentItem.PropertyChanged += CurrentItem_PropertyChanged; // this.CurrentItem.CurrentItem.CurrentItem.PropertyChanged += CurrentItem_PropertyChanged;
this.CurrentItem.CurrentItem.CurrentItem.Appearing += CurrentItem_Appearing; // this.CurrentItem.CurrentItem.CurrentItem.Appearing += CurrentItem_Appearing;
this.CurrentItem.CurrentItem.CurrentItem.BindingContextChanged += CurrentItem_BindingContextChanged; // this.CurrentItem.CurrentItem.CurrentItem.BindingContextChanged += CurrentItem_BindingContextChanged;
} //}
private void CurrentItem_BindingContextChanged(object sender, EventArgs e) //private void CurrentItem_BindingContextChanged(object sender, EventArgs e)
{ //{
Debug.WriteLine(e.ToString()); // Debug.WriteLine(e.ToString());
} //}
private void CurrentItem_Appearing(object sender, EventArgs e) //private void CurrentItem_Appearing(object sender, EventArgs e)
{ //{
Debug.WriteLine(e.ToString()); // Debug.WriteLine(e.ToString());
} //}
private void CurrentItem_PropertyChanged(object sender, PropertyChangedEventArgs e) //private void CurrentItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{ //{
Debug.WriteLine(e.PropertyName); // Debug.WriteLine(e.PropertyName);
} //}
protected bool SetProperty<T>(ref T backingStore, T value, //protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName]string propertyName = "", // [CallerMemberName]string propertyName = "",
Action onChanged = null) // Action onChanged = null)
{ //{
if (EqualityComparer<T>.Default.Equals(backingStore, value)) // if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false; // return false;
backingStore = value; // backingStore = value;
onChanged?.Invoke(); // onChanged?.Invoke();
CallOnPropertyChanged(propertyName); // CallOnPropertyChanged(propertyName);
return true; // return true;
} //}
#region INotifyPropertyChanged //#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged; //public event PropertyChangedEventHandler PropertyChanged;
protected void CallOnPropertyChanged([CallerMemberName] string propertyName = "") //protected void CallOnPropertyChanged([CallerMemberName] string propertyName = "")
{ //{
var changed = PropertyChanged; // var changed = PropertyChanged;
if (changed == null) // if (changed == null)
return; // return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName)); // changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
} //}
#endregion //#endregion
} }
} }