Xamarin Forms Frame not expanding with content - user-interface

I'm new to Xamarin Forms, and I've met my first challenge. I want a Frame around my Stacklayout within a Listview. When the user selects an item in the Listview I want some controls to appear. This works fine without the Frame, but the Frame does not expand when the controls appear. How can I change or get around this behavior?
Code below.
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MVVMTest"
x:Class="MVVMTest.MainPage">
<StackLayout>
<ListView HasUnevenRows="True" SelectedItem="{Binding SelectedViewItem, Mode=TwoWay}" ItemsSource="{Binding Items}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame BackgroundColor="White" BorderColor="Black">
<StackLayout>
<Label Text="{Binding Name}"></Label>
<Entry Text="{Binding Details}" IsVisible="{Binding ShowDetails}"></Entry>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
XAML.cs
namespace MVVMTest
{
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new ViewModel()
{
Items = new List<ViewModelItem>()
{
new ViewModelItem()
{
Name = "Test",
Details = "details"
},
new ViewModelItem()
{
Name = "Test2",
Details = "details2"
}
}
};
InitializeComponent();
}
}
}
Model:
namespace MVVMTest
{
public class ViewModel : INotifyPropertyChanged
{
private ViewModelItem _selectedViewItem;
private List<ViewModelItem> _items;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ViewModelItem SelectedViewItem
{
get
{
return _selectedViewItem;
}
set
{
_selectedViewItem = value;
OnPropertyChanged();
if (value != null)
{
value.ShowDetails = !value.ShowDetails;
SelectedViewItem = null;
}
}
}
public List<ViewModelItem> Items
{
get
{
return _items;
}
set
{
_items = value;
OnPropertyChanged();
}
}
public ViewModel()
{
}
}
public class ViewModelItem : INotifyPropertyChanged
{
private bool _showDetails;
private string _details;
private string _name;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged();
}
}
public bool ShowDetails
{
get
{
return _showDetails;
}
set
{
_showDetails = value;
OnPropertyChanged();
}
}
public string Details
{
get
{
return _details;
}
set
{
_details = value;
OnPropertyChanged();
}
}
}
}

I ended up using the PropertyChanged event to react to when the ListView was displayed or hidden. In the eventhandler, I set the HeightRequest of the Frame and this forces it to resize itself.
Alternative solution/help can be found here:
https://forums.xamarin.com/discussion/comment/366577
XAML:
<StackLayout>
<ListView HasUnevenRows="True" SelectedItem="{Binding SelectedViewItem, Mode=TwoWay}" ItemsSource="{Binding Items}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame BackgroundColor="White" BorderColor="Black" Margin="2" Padding="2" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<StackLayout>
<Label Text="{Binding Name}"></Label>
<ListView HasUnevenRows="True" Margin="2" ItemsSource="{Binding DetailObjects}" IsVisible="{Binding ShowDetails}" PropertyChanged="ListView_PropertyChanged">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Entry Text="{Binding Details}"></Entry>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Code behind:
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new ViewModel()
{
Items = new List<ViewModelItem>()
{
new ViewModelItem()
{
Name = "Test",
DetailObjects = new List<ViewModelItemDetails>
{
new ViewModelItemDetails
{
Details = "details1"
},
new ViewModelItemDetails
{
Details = "details2"
}
}
},
new ViewModelItem()
{
Name = "Test2",
DetailObjects = new List<ViewModelItemDetails>
{
new ViewModelItemDetails
{
Details = "details1"
},
new ViewModelItemDetails
{
Details = "details2"
}
}
}
}
};
InitializeComponent();
}
private void ListView_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!(sender is ListView list)) return;
if (e.PropertyName == ListView.IsVisibleProperty.PropertyName)
{
Element parent = list;
Frame frame = null;
while (frame == null && parent != null)
{
if (parent is Frame) frame = parent as Frame;
parent = parent.Parent;
}
if (list.IsVisible)
{
list.HeightRequest = list.ItemsSource.Cast<ViewModelItemDetails>().Count() * 50;
if (frame != null) frame.HeightRequest = list.HeightRequest + 50;
}
else
{
if (frame != null) frame.HeightRequest = 50;
}
}
}
}

Related

Pushing ImageButton makes the image very small [Xamarin]

Please check the GIF for the problem.
I am actually using two imagebutton here and change IsVisible, since I couldn't accomplish swapping the image by Binding on the source.
ViewModel:
public bool IsAudioPlaying
{
get => player.IsPlaying;
}
...
public void PlayOrPause()
{
if (player.IsPlaying)
player.Pause();
else
player.Play();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsAudioPlaying"));
}
XAML:
<ImageButton AbsoluteLayout.LayoutBounds=".5, 0, 100, 100" AbsoluteLayout.LayoutFlags="PositionProportional" Source="play.png" Padding="20" WidthRequest="80" HeightRequest="80"
CornerRadius="40" VerticalOptions="Center" HorizontalOptions ="Center" BackgroundColor="#cea448" Clicked="PlayOrPause" Margin="10" IsVisible="{Binding IsAudioPlaying, Converter={StaticResource InverseBoolConverter}}" />
<ImageButton AbsoluteLayout.LayoutBounds=".5, 0, 100, 100" AbsoluteLayout.LayoutFlags="PositionProportional" Source="pause.png" Padding="20" WidthRequest="80" HeightRequest="80"
CornerRadius="40" VerticalOptions="Center" HorizontalOptions ="Center" BackgroundColor="#cea448" Clicked="PlayOrPause" Margin="10" IsVisible="{Binding IsAudioPlaying}" />
I am actually using two imagebutton here and change IsVisible, since I couldn't accomplish swapping the image by Binding on the source.
Create a View Model.
public class ViewModel : INotifyPropertyChanged
{
private bool _isAudioPlaying;
public bool IsAudioPlaying
{
get
{
return _isAudioPlaying;
}
set
{
_isAudioPlaying = value;
OnPropertyChanged("IsAudioPlaying");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Use ObservableCollection to update.
ObservableCollection<ViewModel> observableCollection { get; set; }
public MainPage()
{
InitializeComponent();
observableCollection = new ObservableCollection<ViewModel>()
{
new ViewModel(){ IsAudioPlaying=true}
};
this.BindingContext = observableCollection;
}
private void PlayOrPause(object sender, EventArgs e)
{
if (observableCollection[0].IsAudioPlaying == true)
{
observableCollection[0].IsAudioPlaying = false;
imageButton.Source = "pause.png";
}
else
{
observableCollection[0].IsAudioPlaying = true;
imageButton.Source = "play.png";
}
}

Data binding for listview in xamarin

I am trying to populate listview with database table in xamarin forms app
I am getting null pointer exception
Below is XAML for listview
<ListView x:Name="_listView"
ItemsSource="{Binding itemsInList}"
Grid.Column="0"
Grid.Row="0"
SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Grid.Column="0" Grid.Row="0" />
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Below is xaml.cs(code behind)
public List <ServiceProvider> itemlist;
public List <ServiceProvider> itemsInList
{
get {return itemlist;}
}
protected override void OnAppearing()
{
base.OnAppearing();
ExpensesDatabase dbcon = new ExpensesDatabase(completePath);
itemlist = dbcon.GetItems(completePath);
// _listView.ItemsSource = itemlist;
}
Below is db file
public class ExpensesDatabase
{
readonly SQLiteConnection database;
public ExpensesDatabase(string dbPath)
{
database = new SQLiteConnection(dbPath);
database.CreateTable < ServiceProvider > ();
}
public List < ServiceProvider > GetItems(string dbPath)
{
return database.Table < ServiceProvider > ().ToList();
}
}
Data is not displayed in listview
If you want the ListView to automatically update as items are added, removed and changed in the underlying list, you'll need to use an ObservableCollection. ObservableCollection is defined in System.Collections.ObjectModel and is just like List, except that it can notify ListView of any changes:
public ObservableCollection<ServiceProvider> itemsInList { get; set; }
Then make sure you have set the right bindingContext and initialized the ObservableCollection:
public MainPage()
{
InitializeComponent();
itemsInList = new ObservableCollection<ServiceProvider>();
BindingContext = this;
}
I write a sample to test and it works on my side, you can have a look at the full code:
public partial class MainPage : ContentPage
{
public ObservableCollection<ServiceProvider> itemsInList { get; set; }
public MainPage()
{
InitializeComponent();
itemsInList = new ObservableCollection<ServiceProvider>();
BindingContext = this;
}
protected override void OnAppearing()
{
base.OnAppearing();
itemsInList.Add(new ServiceProvider() { Name= "a"});
}
}
public class ServiceProvider : INotifyPropertyChanged
{
string name;
public event PropertyChangedEventHandler PropertyChanged;
public ServiceProvider()
{
}
public String Name
{
set
{
if (name != value)
{
name = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
get
{
return name;
}
}
}
Feel free to ask me any question if you still can't solve it.

How to move this Selected Item Changed Events from Pages into ViewModel?

I have this code for handling Item Selected on ListView and once selected will redirect to other page with an Id.
I can do this in Pages level BUT I want to move this to ViewModel. How do I do this?
ActivitiesPage.xaml:
<ContentPage.ToolbarItems>
<ToolbarItem x:Name="TbSearch" Icon="search.png" Command="{Binding SearchBtnClicked}"></ToolbarItem>
<ToolbarItem x:Name="TbAdd" Icon="add.png" Command="{Binding AddBtnClicked}"></ToolbarItem>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<!--<ListView ItemsSource="{Binding Items}" CachingStrategy="RecycleElement" ItemSelected="LvActivities_ItemSelected">-->
<ListView ItemsSource="{Binding Items}" CachingStrategy="RecycleElement" SelectedItem="{Binding NameSelectedItem}">
<ListView.Behaviors>
<extended:InfiniteScrollBehavior IsLoadingMore="{Binding IsBusy}" />
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Footer>
<Grid Padding="5" IsVisible="{Binding IsBusy}">
<!-- Footer HeightRequest must be 0 when not visible -->
<Grid.Triggers>
<Trigger TargetType="Grid" Property="IsVisible" Value="False">
<Setter Property="HeightRequest" Value="0" />
</Trigger>
</Grid.Triggers>
<Label Text="Loading..." TextColor="Crimson" FontSize="Large"
VerticalOptions="Center" HorizontalOptions="Center" />
</Grid>
</ListView.Footer>
</ListView>
</ContentPage.Content>
ActivitiesPage.xaml.cs
public partial class ActivitiesPage : ContentPage
{
public ObservableCollection<Activity> Activities;
public ActivitiesPage ()
{
InitializeComponent();
BindingContext = new ActivityViewModel(Navigation);
}
private void LvActivities_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var selectedActivity = e.SelectedItem as Activity;
Navigation.PushAsync(new ActivityDetailPage(selectedActivity.Id));
}
}
ActivityViewModel.cs
public class ActivityViewModel : BaseViewModel
{
private const int PageSize = 10;
private int totalRecords;
private readonly ApiService apiService = new ApiService();
public InfiniteScrollCollection<Activity> Items { get; }
public INavigation Navigation { get; set; }
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set
{
_isBusy = value;
OnPropertyChanged();
}
}
public ICommand SearchBtnClicked
{
protected set;
get;
}
public ICommand AddBtnClicked
{
protected set;
get;
}
public ActivityViewModel(INavigation navigation)
{
this.Navigation = navigation;
Items = new InfiniteScrollCollection<Activity>
{
OnLoadMore = async () =>
{
IsBusy = true;
int page = Items.Count / PageSize;
ActivityResult activityResult = await apiService.GetActivities("-CreatedDate", page+1, PageSize);
IsBusy = false;
return activityResult.Results;
},
OnCanLoadMore = () =>
{
return Items.Count < totalRecords;
}
};
DownloadDataAsync();
this.SearchBtnClicked = new Command(async () => await GotoSearchPage());
this.AddBtnClicked = new Command(async () => await GotoAddPage());
}
public async Task GotoSearchPage()
{
await Navigation.PushAsync(new ActivitySearchPage());
}
public async Task GotoAddPage()
{
await Navigation.PushAsync(new ActivityAddPage());
}
private async Task DownloadDataAsync()
{
ActivityResult items = await apiService.GetActivities("-CreatedDate", 1, PageSize);
totalRecords = items.Metadata.TotalRecords;
Items.AddRange(items.Results);
}
Create a SelectedItem property in the view model
private Activity selectedActivity = null;
public Activity SelectedItem {
get { return selectedActivity; }
set {
selectedActivity = value;
NotifyPropertyChanged(); //assumption here
if(selectedActivity != null) {
Navigation.PushAsync(new ActivityDetailPage(selectedActivity.Id));
}
}
}
that can be bound to the list view
<ListView ItemsSource="{Binding Items}"
CachingStrategy="RecycleElement"
SelectedItem="{Binding SelectedItem}">
<!-- ...omitted for brevity -->
</ListView>
This will allow the event handler to be removed from the View's code behind.

Xamarin Forms - remove extra space / embedded ListView

I am trying to figure out how to remove the white space you see in the image below (surrounded by a red rectangle). Notice I have a ListView embedded in a parent ListView.
XAML
<ListView x:Name="___listview" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Button Image="{Binding ImageName}" Command="{Binding ShowDetailsCommand}" />
<ListView ItemsSource="{Binding Notes}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Note}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This probably isn't needed, but here is the model...
MODEL
namespace ViewCellClick
{
public class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Model : ModelBase
{
public Model()
{
_imageName = "ellipses_vertical.png";
_showDetails = true;
ShowDetailsCommand = new Command(() =>
{
ShowDetails = !_showDetails;
ImageName = (_imageName == "ellipses_vertical.png")
? "ellipses_horizontal.png"
: "ellipses_vertical.png";
});
}
bool _showDetails;
public bool ShowDetails
{
get { return _showDetails; }
set { if (_showDetails != value) { _showDetails = value; OnPropertyChanged("ShowDetails"); } }
}
string _imageName;
public string ImageName
{
get { return _imageName; }
set { if (_imageName != value) { _imageName = value; OnPropertyChanged("ImageName"); } }
}
public ICommand ShowDetailsCommand { get; set; }
List<ChildModel> _notes;
public List<ChildModel> Notes { get { return _notes; } set { _notes = value; } }
}
public class ChildModel : ModelBase
{
public ChildModel(string note) { _note = note; }
string _note;
public string Note
{
get { return _note; }
set { if (_note != value) { _note = value; OnPropertyChanged("Note"); } }
}
}
}
You can't do this with Xamarin.Forms.ListView and nesting them is not supported. Really on iOS this would be very difficult and I'm not sure you could get it working without some weird gesture behavior.

Image can't be loaded in ListView in Xamarin?

I am trying to show a list of images in my UWP Xamarin project.
I don't want to use ImageCell.
That's a sample code from Xamarin Forum.
But I can't complete this code to run successfully.
Here is my code.
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="#eee"
Orientation="Vertical">
<StackLayout Orientation="Horizontal">
<Image Source="{Binding image}" />
<Label Text="{Binding title}"
TextColor="#f35e20" />
<Label Text="{Binding subtitle}"
HorizontalOptions="EndAndExpand"
TextColor="#503026" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class ImageItem {
string title;
ImageSource image;
string subtitle;
}
ImageItem a= new ImageItem();
a.title = "XXX";
a.image = ImageSource.FromFile(String.Format("{0}{1}.png", Device.OnPlatform("Icons/", "", "Assets/"), "noimage"));
a.subtitle = "XXX";
list.Add(a);
listview.itemsSource = list;
I have noimage.png in Assets folder of UWP Xamarin Project.
How can I do?
I believe you will need ImageItem to implement the INotifyPropertyChanged interface if you want to use bindings. Can you try setting up the class ImageItem like so:
public class ImageItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string _title;
public string title
{
get
{
return _title;
}
set
{
if (_title != value)
_title = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("title"));
}
}
}
ImageSource _image;
public string image
{
get
{
return _image;
}
set
{
if (_image != value)
_image = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("image"));
}
}
}
string _subtitle;
public string subtitle
{
get
{
return _subtitle;
}
set
{
if (_subtitle != value)
_subtitle = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("subtitle"));
}
}
}
}

Resources