xamarin, How to smoothly upload content to StackLayout - c#

I have a large database and I need to organize searching accounts from my application. App is loaded data dynamically. NetworkBackgroundWorker is a class that send requeste to the server (with database). This class uses BackgroundWorker for waiting answer in the background.
//Callback method
Action<string> refToSP = SetParticipants;
//Send a request to the server for getting account data
NetworkBackgroundWorker.InvokeService(
query,
requestURL,
methodName,
refToSP);
The SetParticipants method is using another BackgroundWorker for add new accounts to the mainStackLayout in the background.
//SetParticipants - This is a method that will be call from the BackgroundWorker
//participantsJSON - Data represented as a JSON code
public void SetParticipants(string participantsJSON)
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork +=
new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerAsync(participantsJSON);
}
And the method for adding new accounts to the MainStackLayout
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
List<ParticipantsTable> participantsTable =
JsonSerializer.Deserialize<List<ParticipantsTable>>(e.Argument.ToString());
for (int i = 0; i < participantsTable.Count; i++)
{
BoxView boxView = new BoxView();
boxView.BackgroundColor = Color.LightGreen;
Label labelParticipantName = new Label();
labelParticipantName.Text =
participantsTable[i].FirstName_ + " " + participantsTable[i].LastName_;
labelParticipantName.FontSize = 20;
labelParticipantName.VerticalOptions = LayoutOptions.StartAndExpand;
labelParticipantName.HorizontalOptions = LayoutOptions.StartAndExpand;
Label labelParticipantPhone = new Label();
labelParticipantPhone.Text =
participantsTable[i].PhoneNumber_;
labelParticipantPhone.FontSize = 20;
labelParticipantPhone.VerticalOptions = LayoutOptions.StartAndExpand;
labelParticipantPhone.HorizontalOptions = LayoutOptions.StartAndExpand;
Label labelSelect = new Label();
labelSelect.Text = "Select: ";
labelSelect.FontSize = 20;
labelSelect.VerticalOptions = LayoutOptions.Start;
labelSelect.HorizontalOptions = LayoutOptions.Start;
CheckBox checkBox = new CheckBox();
checkBox.VerticalOptions = LayoutOptions.Start;
checkBox.HorizontalOptions = LayoutOptions.Start;
StackLayout stackLayout = new StackLayout();
stackLayout.Orientation = StackOrientation.Horizontal;
stackLayout.Children.Add(labelSelect);
stackLayout.Children.Add(checkBox);
var container = new Grid();
container.Children.Add(boxView, 0, 0);
container.Children.Add(labelParticipantName, 0, 0);
container.Children.Add(labelParticipantPhone, 0, 1);
container.Children.Add(stackLayout, 0, 2);
Grid.SetRowSpan(boxView, 3);
mainStackLayout.Children.Add(container);
}
}
I do not have idea why, but scrolling is working not smoothly in the app.
https://www.youtube.com/watch?v=x1iEHFPINnE
How to make smooth scrolling?

#Lucas Zhang - "Put container in the ScrollView or ListView instead of StackLayout".
This recommendation helped to get rid of the scroll jumping.

Related

C# WPF Textbox click Event

I create a stackpanel, and put some controls and 1 of these is a textbox, programaticly.
How can i create an event that, when i click on textbox i delete the stackpanel and everything inside?
Here is my code...
System.Windows.Controls.StackPanel Defesa = new StackPanel();
Defesa.Height = 120;
Defesa.Width = 140;
Panel_DE.Children.Add(Defesa);
Defesa.Background = new
SolidColorBrush((Color)ColorConverter.
ConvertFromString("#FF000000"));
Defesa.Margin = new Thickness(20, 0, 0, 0);
Ellipse Foto = new Ellipse();
Foto.Height = 80;
Foto.Width = 80;
Foto.StrokeThickness = 2;
SolidColorBrush borda = new SolidColorBrush();
borda.Color = Colors.White; ;
Foto.Stroke = borda;
Defesa.Children.Add(Foto);
ImageBrush camera = new ImageBrush();
camera.ImageSource = new BitmapImage(new
Uri(#"C:\Users\Vitor\documents\visual studio 2013\Projects\Manager
Treinador\Manager Treinador\Icons\photo-camera w.png"));
Foto.Fill = camera;
System.Windows.Controls.TextBlock Nome_def = new TextBlock();
Nome_def.Text = def_name;
Nome_def.Foreground = new
SolidColorBrush((Color)ColorConverter.ConvertFromString
("#FFF9F4F4"));
Nome_def.HorizontalAlignment = HorizontalAlignment.Center;
Defesa.Children.Add(Nome_def);
System.Windows.Controls.StackPanel Panel = new StackPanel();
Panel.Orientation = Orientation.Horizontal;
Defesa.Children.Add(Panel);
System.Windows.Controls.TextBlock But_Delet = new TextBlock();
But_Delet.Text = "X";
But_Delet.FontWeight = FontWeights.Bold;
But_Delet.Foreground = new
SolidColorBrush((Color)ColorConverter.ConvertFromString
("#FFF90707"));
Panel.Children.Add(But_Delet);
But_Delet.HorizontalAlignment = HorizontalAlignment.Left;
But_Delet.Cursor = Cursors.Hand;
But_Delete is the text box that i want to remove all...
Thanks
Since a TextBlock does not have a click event, you will need to simulate this by using OnPreviewMouseDown event. To do this:
add this to the end of your code:
But_Delet.PreviewMouseDown += ButDeletOnPreviewMouseDown;
Then add this event handler:
private void ButDeletOnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Panel_DE.Children.Remove(Defesa);
}
However, if there is a chance you will need to restore these controls, it would better to hide them using this event handler instead:
private void ButDeletOnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Defesa.Visibility = Visibility.Hidden;
}

How to set different events for dynamically created element

Im trying to create event with different index for dynamically created GroupBox. With my actual code event for every groupbox is that same. How can i make event with different index for every groupbox? My Code:
public void LoadGry()
{
// GroupBox groupbox = new GroupBox();
Label nazwagry = new Label();
for(int i = 0; i < myCollection.Count; i++)
{
GroupBox groupbox = new GroupBox();
groupbox.Text = myCollection[i];
groupbox.Size = new Size(290, 131);
groupbox.Location = new Point(6, 150 * (myCollection.Count - i - 1));
groupbox.ForeColor = Color.White;
Label label1 = new Label();
label1.Text = groupbox.Text;
label1.AutoSize = true;
label1.Location = new Point(groupbox.Location.X + 80, groupbox.Location.Y + 20);
groupbox.Controls.Add(label1);
Gry.Controls.Add(label1);
PictureBox picturebox = new PictureBox();
picturebox.Location = new Point(groupbox.Location.X + 5, groupbox.Location.Y + 20);
picturebox.Size = new Size(75, 75);
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
picturebox.LoadAsync(myCollection3[i]);
groupbox.Click += new EventHandler(delegate {groupboxclick(groupbox, picturebox, i);});
Label label2 = new Label();
label2.Text = "Status: " + "Aktualny";
label2.ForeColor = Color.Green;
label2.AutoSize = true;
label2.Location = new Point(label1.Location.X, label1.Location.Y + 20);
Gry.Controls.Add(label2);
Label zapiszopis = new Label();
zapiszopis.Text = myCollection4[i];
zapiszopis.Visible = false;
Gry.Controls.Add((Control)groupbox);
//MessageBox.Show("pokaz mi wysokosc");
}
}
private void groupboxclick(GroupBox groupbox, PictureBox picturebox, int itest)
{
groupbox.ForeColor = Color.Aqua;
this.pictureBox1.BackgroundImage = picturebox.BackgroundImage;
opishacka.Text = myCollection4[itest];
}
The problem is that the event setup is using the variable K value. For use the number instead you probably needs to create an expression manually to use the current value in each case.
BUT
You can easily do what you want using the following properties to attach values to controls.
1-) Tag in WinForms & WPF:
// Setup
pictureBox.Tag = i;
// Event
int i = (int) pictureBox.Tag;
2-) ViewState in WebForms
// Setup
ViewState[pictureBox.UniqueID] = i;
// Event
int i = (int) ViewState[pictureBox.UniqueID];
You can use many other techniques. I only post one for each popular framework. I guest that you are in a WinFors project.
Hope this help!

Unexpected NullReferenceException / InvocationTargetException

I have a pointing to null error but i dont see where the problem is since everything gets initalised before used. the points where the error acures i have given a blockquote. Like always im thankfull for every help.
Button topAddBut = null;
//Button botAddBut = null;
Button loadBut = null;
Button saveBut = null;
StackPanel topSP = null;
//StackPanel botSP = null;
public MainWindow()
{
InitializeComponent();
loadBut = new Button { Content = "Load", Width = 70, Height = 23 };
Canvas.SetRight(loadBut, 160);
Canvas.SetBottom(loadBut, 24);
canvas1.Children.Add(loadBut);
saveBut = new Button { Content = "Save", Width = 70, Height = 23 };
Canvas.SetRight(saveBut, 80);
Canvas.SetBottom(saveBut, 24);
canvas1.Children.Add(saveBut);
StackPanel topSP = new StackPanel { Width = 400, Height = 50 };
Canvas.SetLeft(topSP, 160);
Canvas.SetTop(topSP, 100);
AddWrapPanelTop();
AddTextBoxTop();
AddTopButton();
}
void AddTextBoxTop()
{
TextBox txtB1 = new TextBox();
txtB1.Text = "Text";
txtB1.Width = 75;
txtB1.Height = 75;
WrapPanel wp = (WrapPanel)topSP.Children[0];
wp.Children.Add(txtB1);
}
void AddWrapPanelTop()
{
WrapPanel myWrapPanel = new WrapPanel();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);
myWrapPanel.Background = System.Windows.Media.Brushes.Magenta;
myWrapPanel.Orientation = Orientation.Horizontal;
myWrapPanel.Width = 4000;
myWrapPanel.HorizontalAlignment = HorizontalAlignment.Left;
myWrapPanel.VerticalAlignment = VerticalAlignment.Top;
topSP.Children.Add(myWrapPanel);
}
void AddTopButton()
{
TextBox txtB1 = new TextBox();
txtB1.Background = System.Windows.Media.Brushes.Magenta;
txtB1.Text = "Text";
txtB1.Width = 75;
txtB1.Height = 75;
topAddBut = new Button();
topAddBut.Click += new RoutedEventHandler(this.TopClick);
topAddBut.Content = "Add";
topAddBut.Width = 75;
// Add the buttons to the parent WrapPanel using the Children.Add method.
WrapPanel wp = (WrapPanel)topSP.Children[0];
wp.Children.Add(txtB1);
wp.Children.Add(loadBut);
this.topSP.Children.Add(wp);
}
void TopClick(Object sender, EventArgs e)
{
TextBox txtB1 = new TextBox();
txtB1.Background = System.Windows.Media.Brushes.Magenta;
txtB1.Text = "Text";
txtB1.Width = 75;
txtB1.Height = 75;
Button s = (Button)sender;
WrapPanel wp = (WrapPanel)s.Parent;
wp.Children.Remove(s);
wp.Children.Add(txtB1);
AddTopButton();
// Add the buttons to the parent WrapPanel using the Children.Add method.
}
}
}
You define the following:
StackPanel topSP = null;
Then you have
StackPanel topSP = new StackPanel { Width = 400, Height = 50 };
This is in your local scope though so will be destroyed when you exit the function
Finally you have
topSP.Children.Add(myWrapPanel);
This will still be set to null which is why your error occurs. Basically you are creating a local version of the same variable.
In order to resolve simply change the second definition to:
topSP = new StackPanel { Width = 400, Height = 50 };

Create an event handler for control created programmatically

I am working on a WPF application and what I want is if a specific Radio Button from group A is selected the program creates a second set of Radio Buttons call them group B and at the same time a disabled textbox. Now I want to create an event so if the user Selects option 3 from Group B the text box becomes enabled and when it is unselected it disables again. Now I have the working programmatically but when I try to create the event handlers I am referencing a non-existent control and it won't build. I am trying to use this.textBox.IsEnabled = true/false; to enable/disable the textbox. So just to make sure the actual question is clear. How can I enable/disable a textbox which doesn't exist at build/runtime?
My Events:
private void AllowRegion(object sender, RoutedEventArgs e)
{
this.SpecRegionText.IsEnabled = true;
}
private void DisallowRegion(object sender, RoutedEventArgs e)
{
this.SpecRegionText.IsEnabled = false;
}
Creating the controls:
private void AddSpecificControls()
{
Grid grid = (Grid)this.SpecsGrid;
RadioButton recruitmentEnabled = (RadioButton)this.RecruitmentEnabled;
if ((bool)recruitmentEnabled.IsChecked)
{
RadioButton newNations = new RadioButton();
newNations.Margin = new Thickness(10, 10, 0, 0);
newNations.HorizontalAlignment = HorizontalAlignment.Left;
newNations.Name = "NewNations";
newNations.GroupName = "RecruitType";
newNations.Content = "New Nations";
newNations.Width = 124;
grid.Children.Add(newNations);
RadioButton reFound = new RadioButton();
reFound.Margin = new Thickness(10, 30, 0, 0);
reFound.HorizontalAlignment = HorizontalAlignment.Left;
reFound.Name = "Refound";
reFound.GroupName = "RecruitType";
reFound.Content = "Refounded Nations";
reFound.Width = 124;
grid.Children.Add(reFound);
RadioButton specRegionRadio = new RadioButton();
specRegionRadio.Margin = new Thickness(10, 50, 0, 0);
specRegionRadio.HorizontalAlignment = HorizontalAlignment.Left;
specRegionRadio.VerticalAlignment = VerticalAlignment.Top;
specRegionRadio.Name = "SpecRegionRadio";
specRegionRadio.GroupName = "RecruitType";
specRegionRadio.Content = "Specific Region";
specRegionRadio.Width = 124;
specRegionRadio.Height = 23;
specRegionRadio.Checked += new RoutedEventHandler(AllowRegion);
specRegionRadio.Unchecked += new RoutedEventHandler(DisallowRegion);
grid.Children.Add(specRegionRadio);
TextBox specRegionText = new TextBox();
specRegionText.Margin = new Thickness(139, 50, 0, 0);
specRegionText.HorizontalAlignment = HorizontalAlignment.Left;
specRegionText.VerticalAlignment = VerticalAlignment.Top;
specRegionText.Name = "SpecRegionText";
specRegionText.Text = "Region";
specRegionText.Width = 120;
specRegionText.Height = 23;
specRegionText.IsEnabled = false;
grid.Children.Add(specRegionText);
}
}
You can hook delegate inline using lambda but for that you have to declare textBox before radioButton.
TextBox specRegionText = new TextBox();
RadioButton specRegionRadio = new RadioButton();
specRegionRadio.Checked += (s,e) => specRegionText.IsEnabled = true;
specRegionRadio.Unchecked += (s,e) => specRegionText.IsEnabled = false;

Create a bunch of buttons programmatically in C# Win Phone 8 app

I have a problem in my C# file. I have to create 6 buttons programmatically on specific location. but my for loop doesn't work..
just one button shows and not all the buttons.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
//using System.Array;
namespace AimPass
{
public partial class main : PhoneApplicationPage
{
public main()
{
InitializeComponent();
}
private void newbutton(object sender, RoutedEventArgs e)
{
// How many buttons do you want ?
int NumOfButtons = 6;
// X Location of each created button in the panel
int loc = 20;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
btn.Name = "Btn-" + i.ToString();
btn.Size= new Size(50, 20);
btn.Tag = i;
btn.Content = "Browse-" + i.ToString();
btn.location = new Point(5, loc);
}
//Add Click event Handler for each created button
btn.Click += Buttons_Click;
loc += 20;
// Add the created btn to grid
grid.Children.Add(btn);
}
}
}
}
there are 2,3 errors comes..
using System.Windows.Controls.Buttons does not contain a definition of location and size...???
btn.Click += Buttons_Click; does not exist in current context..
And loop is not working..Just one buttons comes except 6 buttons..
I wanna add button on a specific location..So these errors comes to my requirement..
Thanx in advance for solving this..:)
Some time before i have right this ..so take a look you will get what you have read..
it is little bit lengthy but i think it will help you to understand what are you looking for..You can add Row and add button to it in a loop simultaneously but little more is always good..
this is your solution..for your case..but i think you going on wrong way..
private void newbutton()
{
// How many buttons do you want ?
int NumOfButtons = 6;
// X Location of each created button in the panel
StackPanel stkpanel = new StackPanel();
stkpanel.Orientation = Orientation.Horizontal;
int loc = 20;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
btn.Name = "Btn-" + i.ToString();
btn.Height = 20;
btn.Width = 50;
btn.Foreground = new SolidColorBrush(Colors.White);
btn.Content = "btnnum" + i.ToString();
btn.Tag = i;
btn.Content = "Browse-" + i.ToString();
btn.Margin = new Thickness(5 + loc, 5, 5, 5);
btn.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
}
//Add Click event Handler for each created button
btn.Click += btn_Click;
loc += 20;
// Add the created btn to grid
stkpanel.Children.Add(btn);
}
grid.Children.Add(stkpanel);
}
void btn_Click(object sender, RoutedEventArgs e)
{
// throw new NotImplementedException();
}
so..it is better you tried something in some sample projects..what i want to canvey to you..
And as the previous answer says button does not contain properties like loc etc that you want to set..for that Margin is thr..and For Size Height and Width are there..and important thing is..first you write Xaml for what you want to achieve and try to set the properties that you set in xaml during in run time in new project..it will definitely tell you how things work..
Grid grdbooltype = new Grid();
grdbooltype.Name = "Grid_" + keybooltype;
grdbooltype.Margin = new Thickness(0, 20, 20, 0);
grdbooltype.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
grdbooltype.RowDefinitions.Add(new RowDefinition());
TextBlock objtextblock = new TextBlock();
objtextblock.Text = "Select Image";
objtextblock.FontSize = 15;
grdbooltype.Children.Add(objtextblock);
Grid.SetRow(objtextblock, 0);
Grid grdtoggleswitch = new Grid();
grdtoggleswitch.Name = headername;
grdtoggleswitch.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
grdtoggleswitch.ColumnDefinitions.Add(new ColumnDefinition());
TextBlock txtblktoggleswitchleft = new TextBlock();
txtblktoggleswitchleft.FontSize = 15;
txtblktoggleswitchleft.VerticalAlignment = VerticalAlignment.Center;
txtblktoggleswitchleft.Text = headername;
Grid.SetColumn(txtblktoggleswitchleft, 0);
ToggleSwitch toggleswitch = new ToggleSwitch();
toggleswitch.Name = key;
toggleswitch.HorizontalAlignment = HorizontalAlignment.Right;
toggleswitch.Padding = new Thickness(0);
toggleswitch.IsOn = defaultvalue;
toggleswitch.Margin = new Thickness(0, 0, 0, 0);
toggleswitch.OnContent = "On";
toggleswitch.OffContent = "Off";
Grid.SetColumn(toggleswitch, 1);
grdtoggleswitch.Children.Add(txtblktoggleswitchleft);
grdtoggleswitch.Children.Add(toggleswitch);
Grid.SetRow(grdtoggleswitch, 1);
grdbooltype.Children.Add(grdtoggleswitch);
Well, first of all, buttons in Windows Phone don't have size nor location. Why would you think that they do? Instead of Size, you have two properties: Width and Height.
As for location, XAML doesn't work that way. Grid is a special kind of control that creates a layout and you define how many columns and rows you want in your grid. Then you place controls inside individual cells or you can make controls span cells.
Maybe you should learn a bit about XAML first, here is a good starting point: Layout for Windows Phone.
--
EDIT: Adding sample code for placing a button in first row and first column. Note that you have to define grid and column definition either in XAML or code.
grid.Children.Add(btn);
Grid.SetRow(btn, 0);
Grid.SetColumn(btn, 0);

Categories