Buttons that start invisible (Binding to false property) don't fire command when made visible later - binding

In my MainPage.xaml I have a CollectionView in a frame and three image buttons in a frame
I'd like the first button to be visible and when I tap it it makes the other two buttons visible and tap again and make the other two buttons invisible.
Seems pretty straightfoward and I can get it working IF they are all visible at first.
If however the other two buttons start off invisible then the button will not respond.
Aside: I also note that hot reload doesn't seem to work if changes made to the controls(views) inside a frame. I tried without the frames and no difference.
Here's the code:
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Census.ViewModels"
x:Class="Census.MainPage">
<Grid
RowDefinitions="*, 65, 100"
RowSpacing="10">
<Frame Grid.Row="0"
CornerRadius="10"
BorderColor="White"
BackgroundColor="Black"
Margin="0,0,0,0">
<CollectionView ItemsSource="{Binding FriendsOC}"
SelectionMode="Single"
SelectedItem="{Binding SelectedItem}"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding .}" >
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*, 200">
<Label Grid.Column="0"
Text="{Binding FName}"
FontSize="20"
TextColor="Yellow" />
<Label Grid.Column="1"
Text="{Binding LName}"
FontSize="20"
TextColor="Yellow" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Frame>
<Frame Grid.Row="1"
CornerRadius="10"
BorderColor="White"
BackgroundColor="Black"
HeightRequest="60"
Margin="0,0,0,0"
Padding="0,2,0,0">
<Grid ColumnDefinitions="*, *, *">
<ImageButton Grid.Column="0"
Source="nullx.svg"
BorderColor="Yellow"
BorderWidth="2"
WidthRequest="45"
HeightRequest="45"
Command="{Binding RevealCommand}"/>
<ImageButton Grid.Column="1"
Source="nullx.svg"
BorderColor="Green"
BorderWidth="2"
WidthRequest="45"
HeightRequest="45"
IsVisible="{Binding ImportVisible}"
Command="{Binding ImportFriendsCommand}"/>
<ImageButton Grid.Column="2"
Source="nullx.svg"
BorderColor="Red"
BorderWidth="2"
WidthRequest="45"
HeightRequest="45"
IsVisible="{Binding DestroyVisible}"
Command="{Binding DestroyCommand}"/>
</Grid>
</Frame>
<Button Grid.Row="2"
Text="Add"
Command="{Binding AddFriendCommand}"
WidthRequest="100"
Margin="25,25,25,25"/>
</Grid>
</ContentPage>
MainPage.xaml.cs
namespace Census;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new CensusViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
//ImportVisible = false; <--things I tried to no avail
//DestroyVisible = false;
//FriendsList.ItemsSource = await App.Friends.GetFriendsAsync(); //because App.xaml.cs is where th db code is
}
}
and the viewmodel
namespace Census.ViewModels;
public partial class CensusViewModel : ObservableObject
{
[ObservableProperty]
public bool importVisible = true;
[ObservableProperty]
public bool destroyVisible = true;
...
//Reveal Actions
public ICommand RevealCommand => new Command(() =>
{
Console.WriteLine("Reveal");
ImportVisible = !ImportVisible;
DestroyVisible = !DestroyVisible;
});
...
}
This works fine
but if I do
[ObservableProperty]
public bool importVisible = false;
[ObservableProperty]
public bool destroyVisible = false;
It works in terms of hiding the two buttons, but does not respond if I tap the first button, except it does hit the code and change the properties.
Now in my head I am thinking of a question I asked here .net Maui databinding to shell flyout item IsVisible property
I've tried different variation on a theme but haven't been able to figure out what I could do. (Hence why I use the code binding in the codebehind as per the solution.
Just seems so bizarre that it works when the properties start off true and works fine, but not when false.
I've spent a good many hours on this by the way so I do try hard to figure it out myself.

Related

Xamarin IOS Collection View Layout is misaligned at first render

I'm new with xamarin and I have a really weird bug which is making me crazy. I have a Collection View inside a Tab Item from xamarin tool kit.
The item template for the collection view consists on elements inside a Grid. Inside the template I have two grids which each one is visible depending on a boolean (IsStaticCheckList) which tells you if you have custom fields or normal fields.
I put my render function on the tap item command from the tab item (in that way I'm able to force the render each time the checklist item is tapped). The problem is that on IOS version the layout is not rendering well when I open the form for the first time but if we repeat the process it does it.
As an additional info:
I'm using the MVVM pattern so I use commands for all actions inside my view model.
The difference between custom and normal fields. In the UI is that you are able add as many normal fields in the list as you want and edit them. But if we are using custom fields you are not able to do those actions as you have a checklist template selected.
This only happens on IOS version, Android version works as expected.
This issue only happens with normal fields (IsStatiChecklist = true) on ios version. I've been debbuging the code but nothing seems to be wrong. At the end the layout is working as expected at second time. But I'm not able to make it work the first time I open the form.
I attached some pictures for reference
Here it is how it looks at first time (the 3 dot menu does not appear and the other fields neither because the content is using more space that it should) So all the elements are moved in some way to the right.
Render issue
Here it is how it looks after I leave the tab and go again to my checklist tab
Render Second time
Here is a screenshot of the other use case which is working correctly in all cases custom fields screenshot
Here I attached my Item Template XAML Code
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:CheckListAnswerModel">
<Frame>
<Grid
Margin="-10,-20,0,0"
ColumnDefinitions="Auto,*,25,50,Auto"
ColumnSpacing="3">
<Grid
Grid.Column="0"
Grid.ColumnSpan="2"
Padding="20"
IsVisible="{Binding IsStaticCheckList, Source={RelativeSource AncestorType={x:Type viewModels:AddTaskViewModel}}}">
<Label
Grid.Row="0"
IsEnabled="{Binding Complete, Converter={x:StaticResource InvertedBoolConverter}}"
HorizontalOptions="Start"
Text="{Binding Question}"
VerticalOptions="Center"
IsVisible="{Binding ShowLabel}">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding EnableEditionCommand, Source={RelativeSource AncestorType={x:Type viewModels:AddTaskViewModel}}}" CommandParameter="{Binding .}" />
</Label.GestureRecognizers>
<Label.Triggers>
<DataTrigger
Binding="{Binding Complete}"
TargetType="Label"
Value="true">
<Setter Property="TextDecorations" Value="Strikethrough" />
</DataTrigger>
</Label.Triggers>
</Label>
<Entry
Grid.Row="0"
IsEnabled="{Binding Complete, Converter={x:StaticResource InvertedBoolConverter}}"
IsVisible="{Binding ShowEntry}"
Placeholder="Click to add text"
ReturnCommand="{Binding CompleteAddCommand, Source={RelativeSource AncestorType={x:Type viewModels:AddTaskViewModel}}}"
ReturnCommandParameter="{Binding .}"
Text="{Binding Question}"
TextColor="{x:StaticResource PrimaryColor}">
<Entry.Effects>
<effects:BorderlessEntryEffect />
</Entry.Effects>
</Entry>
</Grid>
<ia:Checkbox
Grid.Column="2"
CheckColor="{x:StaticResource WhiteColor}"
FillColor="{x:StaticResource DefaultButtonColor}"
IsChecked="{Binding Complete}"
IsVisible="{Binding Complete}"
OutlineColor="{x:StaticResource DefaultButtonColor}"
Shape="Circle" />
<Image
Grid.Column="3"
IsVisible="{Binding HasTask}"
Scale="0.5"
Source="{x:Static res:Images.CreatedTaskIcon}" />
<ImageButton
Grid.Column="4"
BackgroundColor="Transparent"
Command="{Binding OpenMenuItemCommand, Source={RelativeSource AncestorType={x:Type viewModels:AddTaskViewModel}}}"
CommandParameter="{Binding .}"
Scale="2"
Source="{x:Static res:Images.VerticalMoreIcon}"
VerticalOptions="Center" />
</Grid>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
The Items Source for the collection view is called CheckList which has this definition:
private ObservableCollection<CheckListAnswerModel> _checklist;
public ObservableCollection<CheckListAnswerModel> Checklist
{
get => _checklist;
set
{
_checklist = value;
RaisePropertyChanged(() => Checklist);
}
}
Here is the funtion that tells the view model to add the corresponding items to the Checklist:
private async Task RenderElements()
{
if (_checkListTemplateId > 0)
{
var checklistTemplate = _checkListTemplates.FirstOrDefault(x => x.Id == _checkListTemplateId);
if (checklistTemplate != null)
{
CheckListTemplateText = checklistTemplate.Name;
customFieldAnswer = String.Empty;
_checkListTemplateId = checklistTemplate.Id;
IsStaticCheckList = false;
_checklistAnswerEntities = new List<CheckListAnswerEntity>();
if (Id > 0 && loadAnswers) // taskId > 0
{
_checklistAnswerEntities = await _userTaskManager.GetChecklistAnswerByTaskId(Id);
}
if (_checklistAnswerEntities != null && _checklistAnswerEntities.Count() > 0)
{
await RenderCustomFields(checklistTemplate.ChecklistCustomFields, _checklistAnswerEntities);
}
else
{
await RenderCustomFields(checklistTemplate.ChecklistCustomFields);
}
}
else
{
CheckListTemplateText = AppResources.Label_SelectTemplate;
}
}
else
{
if (HasNormalItems)
{
IsStaticCheckList = true;
Checklist = new ObservableCollection<CheckListAnswerModel>();
foreach (var item in EditTaskParam.TaskListModel.CheckListItems)
{
CheckListAnswerModel model = new CheckListAnswerModel(new CheckListAnswerEntity { TaskId = item.TaskId, ChecklistCustomFieldId = item.Id, Question = item.ItemName });
model.Complete = item.Complete;
model.ShowEntry = false;
model.ShowLabel = true;
model.IsTextEntry = false;
model.IsCustomDropdown = false;
model.IsYesNoEntry = false;
Checklist.Add(model);
}
SetCheckListLabel();
}
else
{
SetCheckListLabel();
}
}
}

ListView moving on Keyboard activation in IOS xamarin forms

I have a problem with Entry and ListView in Xamarin Forms. On Android, it works perfectly but on IOS when Focus is set on Entry, ListView will be moved up like on the image:
I tried to use a render:
How do I keep the keyboard from covering my UI instead of resizing it?
but it didn't solve a problem, in my case because I need ListView moved not the whole page! I also found that this was a known issue:
https://bugzilla.xamarin.com/show_bug.cgi?id=45336
https://www.youtube.com/watch?v=1xwDRT_CnoM&feature=youtu.be
Any suggestions how to turn off moving elements when the keyboard is activated?
And I need Focus set to true in this case!
The code in XAML is next:
<myControls:MyEntry Grid.Row="0" Style="{DynamicResource EntryControlStyle}"
x:Name="CityEntry" AutomationId="SearchCityEntry"
Placeholder="{Binding TravelType, Converter={StaticResource LanguageConverter}, Mode=OneWay}"
Text="{Binding Path=SearchQuery}" />
<myControls:MyListControl
Grid.Row="1"
SeparatorVisibility="None"
HasUnevenRows="True"
IsRefreshing="{Binding IsRefreshing}"
RefreshCommand="{Binding RefreshCommand}"
x:Name="SelectCity"
ItemsSource="{Binding Path=SearchResults}"
SelectedItem="{Binding SelectedCity}">
<myControls:MyListControl.ItemTemplate>
<DataTemplate>
<ViewCell>
<ContentView BackgroundColor="White">
<Grid Margin="10,10,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.4*" />
<ColumnDefinition Width="4*" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0" HorizontalOptions="Start"
VerticalOptions="Start">
<Image HorizontalOptions="Start" VerticalOptions="Start"
Source="{Binding LocationSource,Converter={StaticResource LocationSourceEnumToImageConverter} }" />
</StackLayout>
<Label Grid.Column="1" AutomationId="SearchCityList"
HorizontalOptions="StartAndExpand"
Text="{Binding Path=Name, Mode=TwoWay}"
Style="{DynamicResource EntryControlStyle}" />
</Grid>
</ContentView>
</ViewCell>
</DataTemplate>
and code behind:
protected override void OnAppearing()
{
base.OnAppearing();
CityEntry.Focus();
}
protected override void OnDisappearing()
{
CityEntry.Unfocus();
base.OnDisappearing();
}
protected override bool OnBackButtonPressed()
{
CityEntry.Unfocus();
return base.OnBackButtonPressed();
}

MasterDetail Icon not shown if the page is navigated to from Login Page at start

So my app tries at the start to log in with saved between sessions login information.
Something like this:
public App()
{
if (DoLogin(UserData) == LoginStatus.Success)
MainPage = new NavigationPageNoLine(new MainAppPage());
else
MainPage = new NavigationPageNoLine(new LoginPage());
}
where MainAppPage is a MasterDetailPage.
If there is UserData saved between the sessions of the app, then the MainPage is the MasterDetailsPage where everything is in place and the MasterDetails icon appears as it should be:
But when there is no UserData saved, the LoginPage appears, where, after the login process is completed, I set:
Application.Current.MainPage = new NavigationPageNoLine(new MainAppPage());
Everything is ok except in this case the master details icon does not appear in the page:
The drawer is working perfectly in both cases. Only the icon disappears in the Login scenario.
How to make sure the icon appears in all cases?
Thank you in advance for any help.
Here is the MainAppPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AppName.View.MainAppPage"
xmlns:local="clr-namespace:AppName.Helpers;assembley=Colors"
Title="{i18n:Translate NewsPageTitle}">
<MasterDetailPage.Master>
<ContentPage Title ="Options">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="5,0,5,0">
<ListView IsGroupingEnabled="False"
ItemsSource="{x:Static apploc:Settings.OptionMenuItems}"
IsPullToRefreshEnabled="False"
HasUnevenRows="False"
x:Name="ListViewOptions"
HorizontalOptions="FillAndExpand"
SeparatorVisibility="None"
VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5,5" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="8*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Aspect="AspectFit" Source="{Binding IconSource}" HorizontalOptions="Center" VerticalOptions="Center"/>
<Label Grid.Column="1"
Text="{Binding Title}"
HorizontalOptions="Start"
TextColor="{x:Static local:Colors.PrimaryText}"
VerticalOptions="Center"
FontAttributes="Bold">
<Label.FontSize>
<OnPlatform x:TypeArguments="x:Double" iOS="14" Android="14" WinPhone="11" />
</Label.FontSize>
</Label>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<ContentPage Title ="Feeds">
<AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
...
</AbsoluteLayout>
</ContentPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
and here is my MainAppPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using AppName.Resx;
namespace AppName.View
{
public partial class MainAppPage : MasterDetailPage
{
public MainAppPage()
{
InitializeComponent();
ListViewOptions.ItemSelected += async (sender, e) => await NavigateTo(e.SelectedItem as OptionsMenuItem);
}
private async Task NavigateTo(OptionsMenuItem menuItem)
{
if (menuItem == null)
return;
if (menuItem.TargetType == null)
return;
Page displayPage;
try
{
if (menuItem.TargetType == typeof(WebPage))
displayPage = (Page)Activator.CreateInstance(menuItem.TargetType, menuItem.TargetUri, menuItem.Title);
else
displayPage = (Page)Activator.CreateInstance(menuItem.TargetType);
await Navigation.PushAsync(displayPage, true);
}
finally
{
ListViewOptions.SelectedItem = null;
IsPresented = false;
}
}
}
}

listbox not showing all items windows phone 8.1

I'm trying to populate a listbox using binding in windows phone 8.1. I can't see all of the items in the control.
XAML:
<Grid x:Name="LayoutRoot">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Text="Application Name" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<StackPanel Grid.Row="1" x:Name="ContentRoot" Margin="19,0,19,0">
<ComboBox
x:Name="ComboBox1"
ItemsSource="{Binding}"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
SelectionChanged="ComboBox1_SelectionChanged"
/>
<ListBox x:Name="ListBox1" ItemsSource="{Binding}" Height="1000">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="0">
<TextBlock Text="{Binding GameName}" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
I populate the listbox in code:
private ObservableCollection<Game> _Games = new ObservableCollection<Game>();
public StartPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
ListBox1.DataContext = _Games;
}
....
private async void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var group = _Groups[ComboBox1.SelectedIndex];
games = await DataServer.GetGamesAsync(group.GroupName);
_Games.Clear();
foreach (var game in games.OrderBy(g => g.GameName))
{
_Games.Add(game);
}
}
There are 69 games but I can only see about 28 in the list view in the emulator when I scroll the list. It's clear that there are more items in the list, but I can't scroll to them. Any help is appreciated.
Replace the StackPanel with a Grid and add a couple more RowDefinitions in the second Grid you'll add. StackPanels don't size themselves dynamically, so instead of sizing to the screen, it's just stretched infinitely to the bottom.

Listpicker unclickable

I have written a listbox to display the "Engine Size" of a set of data from an XML sheet, the item binding seems to work, and the listbox works prefectly for the first two options however the rest are completly unclickable.
I have tried breaks in the code and it is showing that clicking on one of the not working values doesnt even trigger the "ListPicker_ChangedSelection" program i have.
The code I have is below.
private void Choose_Engine_Size_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String carenginesize=((enginesize)Choose_Engine_Size.SelectedItem).Esize.ToString();
List<enginesize> enginesize =GetCarData();
foreach (enginesize c in enginesize)
{
if(c.Esize==carenginesize)
{
ConsumptionBox.Text=c.Consumption;
EmmissionsBox.Text=c.Emissions;
}
}
From this is then goes to make some caluclation with the populated values from this.
My Listpicker code is as follows:
<toolkit:ListPicker HorizontalAlignment="Left" Margin="287,22,0,0" x:Name="Choose_Engine_Size" VerticalAlignment="Top" Width="72" SelectionChanged="Choose_Engine_Size_SelectionChanged" Height="Auto" Opacity="1">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border>
<TextBlock Text="{Binding Esize}" FontSize="20" Width="Auto" HorizontalAlignment="Center"/>
</Border>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>

Resources