Button in Custom ViewCell Xamarin Tableview C# - c#

Looking forward to your assistance once again :)
I'm trying to have the buttons on the far right be able to delete their row in the tableview control. Right now they now about which row they are on but I cannot connect this information to the parent. The table view is populated with a custom viewcell.
The custom view cell contains two different pickers, two entry fields and a button. I haven't found a cleaner way to execute this as I have the picker's data which isn't related to the # of rows in the data table control.
Currently when you click a button on the right it posts to the console what row was selected but I don't know of a way to connect that to its parent in order to actually delete that row on the data table
View Cell Code Behind
public partial class RecipeIngredientViewCell : ViewCell
{
ObservableCollection<clIngredient> _listIngredients = new ObservableCollection<clIngredient>();
public ObservableCollection<clIngredient> listIngredients { get { return _listIngredients; } }
ObservableCollection<clUnit> _listUnit = new ObservableCollection<clUnit>();
public ObservableCollection<clUnit> funclistUnit { get { return _listUnit; } }
clRecipeIngredient _recipeIngredient;
int _row;
public RecipeIngredientViewCell(clRecipeIngredient passedrecipeIngredient, ObservableCollection<clIngredient> passedlistIngredients, ObservableCollection<clUnit> passedlistUnits, int row)
{
InitializeComponent();
_listIngredients = passedlistIngredients;
_listUnit = passedlistUnits;
_recipeIngredient = passedrecipeIngredient;
_row = row;
this.BindingContext = _recipeIngredient;
//INGREDIENT PICKER
pickerIngredient.ItemsSource = _listIngredients;
for(int x = 0; x < _listIngredients.Count; x++)
{
if (_listIngredients[x].IngredientName == _recipeIngredient.IngredientName)
{
pickerIngredient.SelectedIndex = x;
}
}
//UNIT PICKER
pickerUnit.ItemsSource = _listUnit;
for (int x = 0; x < _listUnit.Count; x++)
{
if (_listUnit[x].UnitName == _recipeIngredient.UnitName)
{
pickerUnit.SelectedIndex = x;
}
}
}
private void btnDeleteRecipeIngredient_Clicked(object sender, EventArgs e)
{
//NOT IMPLEMENTED YET!
Console.WriteLine(_recipeIngredient.IngredientName + " AT ROW " + _row.ToString());
}
private void txtQuantity_TextChanged(object sender, TextChangedEventArgs e)
{
_recipeIngredient.Quantity = txtQuantity.Text.ToDouble();
}
private void txtComment_TextChanged(object sender, TextChangedEventArgs e)
{
_recipeIngredient.Comments = txtComment.Text;
}
private void pickerIngredient_SelectedIndexChanged(object sender, EventArgs e)
{
_recipeIngredient.IngredientName = pickerIngredient.SelectedItem.ToString();
}
private void pickerUnit_SelectedIndexChanged(object sender, EventArgs e)
{
_recipeIngredient.UnitName = pickerIngredient.SelectedItem.ToString();
}
}
View Cell XAML
<ViewCell 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="RecipeDatabaseXamarin.Views.RecipeIngredientViewCell">
<Grid VerticalOptions="CenterAndExpand" Padding = "20, 0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="75" />
</Grid.ColumnDefinitions>
<Picker Grid.Column = "0" x:Name="pickerIngredient" HorizontalOptions = "StartAndExpand" SelectedIndexChanged="pickerIngredient_SelectedIndexChanged"/>
<Entry Grid.Column = "1" x:Name ="txtQuantity" HorizontalOptions = "StartAndExpand" Text = "{Binding Quantity}" TextChanged="txtQuantity_TextChanged" />
<Picker Grid.Column = "2" x:Name ="pickerUnit" HorizontalOptions = "StartAndExpand" SelectedIndexChanged="pickerUnit_SelectedIndexChanged"/>
<Entry Grid.Column = "3" x:Name="txtComment" HorizontalOptions = "StartAndExpand" Text = "{Binding Comments}" TextChanged="txtComment_TextChanged" WidthRequest="150"/>
<Button Grid.Column = "4" x:Name="btnDeleteRecipeIngredient" HorizontalOptions = "StartAndExpand" Text = "Delete Ingredient" Clicked="btnDeleteRecipeIngredient_Clicked"/>
</Grid>
Code Behind for Page
var section = new TableSection();
for(int i = 0;i<_downloadedRecipeIngredients.Count;i++)
{
var cell = new RecipeIngredientViewCell(downloadedRecipeIngredients[i], listIngredients, listUnit, i);
section.Add(cell);
}
tblData.Root.Add(section);
In the main page code behind I want the button to run a block of code to execute something such as
tblData.Root.del(ROW_INDEX);
Thanks!
I believe I have this solved. Will post the solution when I get back from the 4th weekend.

The solution to this problem is answered on another post. Basically the solution is easier once MVVM is implemented even though it was a pain to get it to work on the picker withing the listView control.
This other thread has sample code which you can run.
Trying to set picker within listview MVVM Xamarin
If anyone runs into the same issue please post and I'll try to respond back as this issue was a PAIN!!!!

I am not a notorious xamarin programmer, but you have your width to auto, which most likely changes the whole grid the moment the width changes. Therefore it will align the buttons differently too.
It seems you could position the horizontalOptions to "End" to at least put the buttons to the end of the screen. If you want to have it always the same, I would give them a certain width per section.

Related

Remove Button Text If There Isn't Enough Space

I'm working with an item template that should display one or more buttons per item. There are three buttons that I want to be displayed on a horizontal line. Each button has an icon and some text.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="LeftButton"
Text="Left Button"
ImageSource="left.png"
HorizontalOptions="Start"/>
<Button x:Name="CenterButton"
Text="Center Button"
ImageSource="center.png"
HorizontalOptions="Center"/>
<Button x:Name="RightButton"
Text="Right Button"
ImageSource="right.png"
HorizontalOptions="End"/>
</Grid>
This is working good so far. The three buttons display the icon and text and they are aligned left, center and right respectively.
Now, I want the buttons to only display the icons, if the container is not wide enough to display all the text. As far as I understand MVVM, this should be the responsibility of the View.
My intended solution would be something like this:
public partial class ItemTemplate : ContentView
// ContentView is our implementation of a UI element.
{
public ItempTemplate()
{
InitializeComponent();
SizeChanged += HandleSizeChanged;
}
private void HandleSizeChanged(object sender, EventArgs e)
{
if (/* not enough space */)
{
LeftButton.Text = string.Empty;
CenterButton.Text = string.Empty;
RightButton.Text = string.Empty;
}
else
{
LeftButton.Text = "Left Button";
CenterButton.Text = "Center Button";
RightButton.Text = "Right Button";
}
}
}
Is there any way to know if the container is wide enough for all three button? If possible, I'd like to use a dynamic solution, because the button text will eventually be translated.
You can place the code into a custom contentview , and decide to hide/show the text in the event LayoutChanged according to the container's width .
Custom View xaml
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="LeftButton" Grid.Column="0" Text="Left Button" ImageSource="dots.png" HorizontalOptions="Start"/>
<Button x:Name="CenterButton" Grid.Column="1" Text="Center Button" ImageSource="dots.png" HorizontalOptions="Center"/>
<Button x:Name="RightButton" Grid.Column="2" Text="Right Button" ImageSource="dots.png" HorizontalOptions="End"/>
</Grid>
Custom View code behind
public partial class MyView : ContentView
{
public MyView()
{
InitializeComponent();
this.LayoutChanged += MyView_LayoutChanged;
}
private void MyView_LayoutChanged(object sender, EventArgs e)
{
var view = sender as View;
if (view.Width < 200)
{
LeftButton.Text = string.Empty;
CenterButton.Text = string.Empty;
RightButton.Text = string.Empty;
}
else
{
LeftButton.Text = "Left Button";
CenterButton.Text = "Center Button";
RightButton.Text = "Right Button";
}
}
}
Scenario : container is large enough.
xmlns:local="clr-namespace:FormsApp"
<local:MyView/>
Scenario : container is small ,wrapped inside another layout .
<Grid HorizontalOptions="Start" WidthRequest="199" >
<local:MyView/>
</Grid>
I solved my problem by using a custom button implementation (mostly because I needed some other additional features).
The custom button contains an Image and a Label. In addition to the standard button features I need, I added these methods to the code-behind:
public void ExpandText() {
Label.IsVisible = true;
}
public void CollapseText() {
Label.IsVisible = false;
}
public bool IsTextCollapsed() {
return !Label.IsVisible;
}
public double GetWidthAsExpanded() {
return Image.Width + Label.Width;
}
In the container's code-behind I check if the button's width fits within its container and collapse/expand accordingly. For that to work, I added containers for each button.
public ItemTemplate() {
InitializeComponent();
LayoutChanged += HandleLayoutChanged;
}
private static void HandleLayoutChanged(object sender, EventArgs e)
{
if (!(sender is ItemTemplate itemTemplate))
{
return;
}
if (itemTemplate.ButtonContainerLeft.Width > itemTemplate.ButtonLeft.GetWidthAsExpanded()
&& itemTemplate.ButtonContainerCenter.Width > itemTemplate.ButtonCenter.GetWidthAsExpanded()
&& itemTemplate.ButtonContainerRight.Width > itemTemplate.ButtonRight.GetWidthAsExpanded())
{
ExpandAllButtons(itemTemplate);
}
else
{
CollapseAllButtons(itemTemplate);
}
}
Because I added ExpandText and CollapseText earlier, I don't have to "remember" what the text inside the button was, because I just collapse the label within the button. GetWidthAsExpanded will always return the necessary width of the button, even if it is collapsed.
side-note 1: I could've just added the width-check within the custom button implementation, but not every ItemTemplate has all buttons and if any label is collapsed, all labels should be collapsed.
side-note 2: I needed button containers either way, because the left button will either be "Mark as Read" or "Mark as Unread" depending on the state of the ItemTemplate data context. So there are actually two buttons in the first container.

How to get access to ToggleSwitch instance within ListView in C# UWP?

I opened the question here but we cannot come to the solution for my problem. I decided to create new question as we came to some assumptions and the former question does not refer to the real problem(we thought it is the problem with binding but as you will read on it is not).
In few words I have a ListView with data from list called jointList.
The list is doing well and it has all the data necessary. (I checked it)
On each row of the ListView I put a ToggleSwitch(in xaml) and then I try to do something with each of the switches.
Each switch should correspond to the data from the same row.
I created Toggled event that should apply to all toggleSwitches like this:
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
foreach (var product in jointList)
{
if (product.IsOn == true)
{
ToggleTest.Text = product.ProductId.ToString(); // this is for testing only, later I would do something with the data retrieved
ToggleTest.Visibility = Visibility.Visible;
}
else
{
ToggleTest.Visibility = Visibility.Collapsed;
}
}
}
But this is making only one toggleSwitch work. It's the switch that corresponds to the last added product to the list ( I am guessing that it is refering to the last Id). The other switches return nothing as if the method was not iterating through the list correctly or as if there was only one switch hooked up.
So, is it possible to get all switches up and running by using just one Toggled event as I attempt to do?
Here's a sample which shows one way.
In this example we have the following Product view model:
public class Product : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
if (value == _name) return;
_name = value;
OnPropertyChanged();
}
}
So just a single Name-property.
Then we have MainPage where we create a collection of products:
private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
{
var items = new ObservableCollection<Product>();
for (int i = 0; i < 9; i++)
{
items.Add(new Product($"item {i}"));
}
this.Items.ItemsSource = items;
}
And the XAML which creates the view:
<ListView Loaded="FrameworkElement_OnLoaded" x:Name="Items">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="RowContent" Text="{Binding Name}"/>
<ToggleSwitch x:Name="Toggle" Grid.Column="1" Toggled="Toggle_OnToggled"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The result:
Now we want to change the text when user toggles the switch. This is done in Toggle_OnToggled-event handler:
private void Toggle_OnToggled(object sender, RoutedEventArgs e)
{
var toggle = (ToggleSwitch) sender;
var dataContext = ((Grid)toggle.Parent).DataContext;
var dataItem = (Product) dataContext;
dataItem.Name = $"Toggled {toggle.IsOn}";
}
So after a few toggles:
Mikael Koskinen has delivered the answer to my problem.
Most of my code was correct and identical to his solution, apart from the last bit that is OnToggled event handler.
Here is the working andd correct handler:
private void Toggle_OnToggled(object sender, RoutedEventArgs e)
{
var toggle = (ToggleSwitch)sender;
var dataContext = ((Grid)toggle.Parent).DataContext;
var dataItem = (ScheduleList)dataContext;
ToggleTest.Text = dataItem.ProductId;
}
My previous version of handler didn't include the important bit, that is dataContext and dataItem.
It works like a charm now.

Add textblock text to favorite list on button click

I have two pages: the first is mainpage.xaml and the second is favoriteslist.xaml.
In mainpage.xaml I have a text block, which shows some dynamic text automatically.
And I have a button also on mainpage.xaml.
From which I want when I click on that button, text appears on text block should go to favorite list in favoriteslist.xaml page.
If text already favorite, which text appears on text block should be removed from favorite list on button click.
So finally I need help to implement this functionality textblock which shows dynamically already created but I only need to know how to develop add to favorite functionality.
Textblock:
<TextBlock x:Name="StringTextBlock" Text="" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" />
Button:
<Button Grid.Row="2" x:Name="AddToFavoritesButton"
Content="Add" Style="{StaticResource ButtonStyle2}" Margin="2"
Click="AddToFavoritesButton_Click"/>
C#
private void AddToFavoritesButton_Click(object sender, RoutedEventArgs e)
{
}
Listbox:
<ListBox x:Name="FavoriteListBox" />
I would use IsolatedStorageSettings to store the list and compare the dynamic text to the list in the isolatedstoragesettings upon button click. Then on FavouritesList page, set itemsource of the listbox to the list in IsolatedStorageSettings.So here are the steps to be followed:
1. Create a model/class to set the dynamic text being shown on the text block
public class favourites
{
public string myText { get; set; }
}
2. In the button click event on MainPage.xaml.cs, first set the dynamic text (where ever you are getting it from) to the text block if you need to and then create the list and/or compare
private void AddToFavoritesButton_Click(object sender, RoutedEventArgs e)
{
//your dynamic text set to textblock
StringTextBlock.Text = myDynamicText;
//Set value of your text to member variable of the model/class
favourites f = new favourites();
f.myText = myDynamicText;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
/*Check if "FavouritesList" key is present in IsolatedStorageSettings
which means already a list had been added. If yes, retrieve the
list, compare each item with your dynamic text, add or remove
accordingly and replace the new list in IsolatedStorageSettings
with same key. */
if (settings.Contains("FavouritesList"))
{
List<favourites> l = (List<favourites>)settings["FavouritesList"];
for(int i = 0; i <= l.Count()-1; i++)
{
if (l[i].Equals(myDynamicText))
{
l.RemoveAt(i);
settings["FavouritesList"] = l;
}
else
{
l.Add(f);
settings["FavouritesList"] = l;
}
}
}
//If no key in IsolatedStorageSettings means no data has been added
//in list and IsolatedStorageSettings. So add new data
else
{
List<favourites> l = new List<favourites>();
l.Add(f);
settings["FavouritesList"] = l;
}
settings.Save();
}
Now all that is left is show the always updated list in the FavouritesList Page. I added a 'NoData' textblock that should be visible when there is nothing in the list. Else the list will be displayed.
In FavouritesList.xaml
<ListBox x:Name="FavoriteListBox" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding myText}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Name="NoData"
Text="No Data"
Visibility="Collapsed"
Width="50"
Height="50"/>
In FavouritesList.xaml.cs
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("FavouritesList"))
{
List<favourites> l = (List<favourites>)settings["FavouritesList"];
if(l.Count!= 0)
{
NoData.Visibility = System.Windows.Visibility.Collapsed;
FavoriteListBox.Visibility = System.Windows.Visibility.Visible;
FavoriteListBox.ItemsSource = l;
}
}
else
{
FavoriteListBox.Visibility = System.Windows.Visibility.Collapsed;
NoData.Visibility = System.Windows.Visibility.Visible;
}
I have not tested this but should definitely work. Hope it helps!

x:Bind in windows 10 Mode One way

I am trying to update the list which is Bound to ListBox , When the scroll bar reaches end.I need to update the list and show the changes in UI also.Here it is not updating automatically.Can someone please help me in fulfilling my requirement.
If i tried to use TwoWay mode, It shows below error:
Error : Invalid binding path 'itemsList' : Cannot bind type 'System.Collections.Generic.List(System.String)' to 'System.Object' without a converter
<ScrollViewer
x:Name="sv"
ViewChanged="OnScrollViewerViewChanged">
<ListBox x:Name="listView"
HorizontalAlignment="Left"
Height="Auto"
VerticalAlignment="Top"
Width="172"
ItemsSource="{x:Bind itemsList, Mode=OneWay}"/>
</ScrollViewer>
and the code
public List<String> itemsList = new List<string>();
private void OnScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var verticalOffset = sv.VerticalOffset;
var maxVerticalOffset = sv.ScrollableHeight; //sv.ExtentHeight - sv.ViewportHeight;
if (maxVerticalOffset < 0 ||
verticalOffset == maxVerticalOffset)
{
// Scrolled to bottom
Util.debugLog("REACHED BOTTOM");
int i;
// itemsList = null;
itemsList.Clear();
for (i = 0; i < 20; i++)
{
itemsList.Add("Item number " + i + 900);
}
}
else
{
// Not scrolled to bottom
// rect.Fill = new SolidColorBrush(Colors.Yellow);
}
}
Here(In below link) is the answer for my question.Thanks alot for all who tried to answer my question.
https://social.technet.microsoft.com/Forums/en-US/7c730558-f933-4483-8d5b-1710d19f99de/xbind-in-windows-10-mode-one-way-i-am-trying-to-update-the-bind-list-when-scrollview-reached-to?forum=wpf

Bound ItemsControl not updating before displaying

I have a UserControl that is comprised of a few bound ItemsControl's and strings, and based on the button that is pressed, different data is displayed. Here is an example of one of the Button's click events:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
}
else
{
WindowTitle = "Left Side";
PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
m_previousScoresWindow.Show();
}
}
There are several of these click event listeners which assigns WindowTitle, PreviousScoresA, and PreviousScoresB with the associated data. The UserControl then binds to them like this:
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresA}"
Grid.Row="1" />
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresB}"
Grid.Row="2" />
<TextBlock FontSize="16" FontWeight="Bold" Height="25"
Margin="5" HorizontalAlignment="Center" Foreground="Black"
Text="{Binding ElementName=ParentForm, Path=PreviousScoresWindowTitle}" />
However, when opening the window, the old data displays for a second before it is updated with the current data. I've even tried adding these calls when calling Hide() on the Window but it didn't seem to help:
WindowTitle = String.Empty;
PreviousScoresA = new ObservableCollection<PreviousScoreData>();
PreviousScoresB = new ObservableCollection<PreviousScoreData>();
Is there any way to ensure that Show() is not called until after the bound data has been updated? Thanks.
As it appears you are using an ObservableCollection, the collection should never be re-initialized. Rather, it should just be cleared and then add the new values; this is what helps keep the collection synchronized when using an ObservableCollection.
This is a bit of a shot in the dark based on your code sample; if you clear the collection when hiding and then refill them with the new values, then you should get the desired effect:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
WindowTitle = string.Empty;
PreviousScoresA.Clear();
PreviousScoresB.Clear();
}
else
{
WindowTitle = "Left Side";
// do not re-initialize the collection; clear and add new values
// PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
// PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
ReFillScores(PreviousScoresA, m_previousLeftWristErosionScoresReaderA);
ReFillScores(PreviousScoresB, m_previousLeftWristErosionScoresReaderB);
m_previousScoresWindow.Show();
}
}
private void ReFillScores (ObservableCollection<PreviousScoreData> collection, IEnumerable<PreviousScoreData> values)
{
collection.Clear();
foreach(PreviousScoreData d in values)
{
collection.Add(d);
}
}

Categories