Databinding WPF C# WPF to labels in Codebehind - c#

I have a list of Accounts with some properties which are saved in a database.
On my Window I´m going to show the Username from the Account list
for (int i = 0; i < liste.Count; i++)
{
Label l = new Label();
l.Height = 30;
l.HorizontalAlignment = HorizontalAlignment.Left;
l.Content = liste[i].Username + "\n";
l.MouseDown += new MouseButtonEventHandler(Selectuser);
l.HorizontalContentAlignment = HorizontalAlignment.Left;
stack.Children.Add(l); // stackpanel in the xaml
SetKnownImageAcc(Convert.ToInt32( liste[i].AccAId)); // add a picture near the username
}
So I have now I MouseButton Event on every label I created but when I click on one of the usernames I the code behind I only can get the content of the Label so I don't know which Account it is exactly.
Sure i can make a loop to check liste[i].Username = this.content
But my Problem then is that i have more accounts and for example I have 2 accounts one facebook and one google but they have the same username how do I know now in the codebehind which account it is where I clicked
A friend said to me that I should try it with databinding but i´m new to coding so I don't know really how to do it or if this works with databinding.
Thanks for your help :)

One way you can do that is setting the Tag property of your label:
l.Tag = liste[i];
Then, you can get your user back in the subscribed method:
var myUser = (User)((Label)sender).Tag;
But your friend is right: Data binding is a much better way. In fact, in most cases, you shouldn't have any code in the code behind file (other than the automatically generated code). Try looking for MVVM on your favorite search engine.

Related

(C#) How to do this in WPF forms?(Looking on Orange5 design)

What im trying to do is design and fuctions(not all) like Orange5 has on a main area(see the link of the picture). This field origionally filled with "FFFF" letters, and the user can write into this cells, and change the data on into by clicking the "write" button. Also i can fill this field by pressing a "read" button, it will read the data from EEPROM . My code on Microcontroller is ready, and i already know how to send/receive/write/read data from/into EEPROM to C#. But i dont know how to relise this on C# with this design and functions. Any help please..
Click Here
You could create a new textbox (or a label that changes into a textbox when clicked if you want to do the extra work) for every 4 bits.
Here's a very crude example:
byte[] data = ... //get your data somehow...
for(int i = 0; i < data.Length; i+=4) {
TextBox tb = new TextBox();
tb.Text = data[i] + data[i+1] + data[i+2] + data[i+3];
grid.Children.Add(tb);
}

Dynamically Create Checkbox With Scrolling

I'm trying to build a form application in Visual Studio 2010 using C#.
The program will be reading a excel file that contains a list of filenames, and will dynamically generate textbox for each filename.
Below is my code, just for clarification. I wanted to make the label a link to the file, that's why I didn't use checkboxes[i].Text = filename
CheckBox[] checkboxes = new CheckBox[fileCount];
Label[] labels = new Label[fileCount];
for (int i = 0; i < fileCount; i++ )
{
//creating a checkbox
checkboxes[i] = new CheckBox();
checkboxes[i].Location = new Point(360, (145 + i * 30));
checkboxes[i].Name = String.Format("checkbox{0}", i.ToString());
this.Controls.Add(checkboxes[i]);
//creating filename label
labels[i] = new Label();
labels[i].Location = new Point(20, (150 + i * 30));
labels[i].Text = existingFiles[i];
labels[i].Width = 330;
this.Controls.Add(labels[i]);
}
Say if fileCount equals to 100, it will make the form really big/long and won't be able to fit properly on most monitors.
Is there a way to make all dynamically generated checkboxes and labels all grouped in a area and just have the user be able to scroll? Something like a panel with scrolling? I don't know if there's anything like that.
I thought about using CheckedListBox, but doing that way I won't be able to make the filename a link. I want the user be able to click on the label and the file will be opened automatically, instead of selecting it.
Any help is appreciated!
Most controls have the AutoScroll property. Set this to true, and the control will automatically add a scrollbar when necessary. You can use the Panel control and add all of your links/checkboxes to that (if you don't want your whole form to scroll).

How do i bind an "Entry Cell" to a custom object using Xamarin?

I have been playing with Xamarin for a short time so far, and i just stumbled into something i couldn't find the answer into their documentation.
I am building a fairly simple app that retrieves "User Data" (username, email, password and so forth) from a RESTfull API and populates a listview with some of the data (This is the point i am at the moment. It works).
The next step is to build a "Edit User" screen, which is invoked uppon selecting (tapping) a user on the Listview i currently have.
I have managed to build a simple view that is basically two Entry Cells showing the data of the user picked into the previous listview screen. That also works.
The problem is that, once i edit the data into the "Entry Cell" it has no reflection into the "User Model" that populated the "entry cell" in first place.
How do i bind those together?
Code Sample:
// Entry Cell of Username (Should be Binded)
EntryCell ecUsername = new EntryCell()
{
Label = "Username:",
Placeholder = "username / login",
Text = _user.Username
};
// Entry Cell of Password (Should be Binded)
EntryCell ecEmail = new EntryCell ()
{
Label = "Email:",
Placeholder = "user email",
Text = _user.Email
};
Some Screenshots:
Once i click into a user, its data gets rendered into the next screen.
I haven't tested this, but something like this should work:
EntryCell ec = new EntryCell ();
ec.BindingContext = _user;
ec.SetBinding (EntryCell.TextProperty, "Username");

ASP.NET:adding controls Dynamicly afther post back with diffrent data

i got a page where the admin can edit some photos i pull from flickr so all the controls are added Dynamiclly.
i have few controls i add to a panel and then add the panel to Form.Controls.
all the data thay are holding come from flickr.
my problem is that, afther a post back the list change and the controls are loading, BUT the Text Box's keep that same data befor the post back even though i get the data from flickr every time.
what wierd for my that if i do this with less textbox every thing work fine.
the list are about 10+ pictures and this numbers can change in the future.
(sorry for the messy code im pretty new to programming)
here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadioButtonList1.AutoPostBack = true;
selectedSetID = getSelectedSetId(RadioButtonList1.SelectedItem.Text);
photoSet = new MyPhotoSet(selectedSetID);
photo = new FlickerImages[photoSet.Count];
for (int j = 0; j < photo.Length; j++)
{
photo[j] = new FlickerImages(photoSet.MediumURLS[j], photoSet.ThumbnailURLS[j], photoSet.Titles[j], photoSet.Descreption[j], photoSet.PhotosID[j]);
panel = photo[j].GetPanelWithEditControls(j);
button = new Button();
button.ID = "sendDataButton" + j;
button.Text = "send data";
button.Click += button_Click;
panel.Controls.Add(button);
Form.Controls.Add(panel);
}
}
else
{
//here is the post back,
every thing load fine.
adding and removing the controls but if the textbox's load in the same place, it hold the same data befor the post back.
RadioButtonList1.AutoPostBack = true;
selectedSetID = getSelectedSetId(RadioButtonList1.SelectedItem.Text);
photoSet = new MyPhotoSet(selectedSetID);
photo = new FlickerImages[photoSet.Count];
for (int i = 0; i < photo.Length; i++)
{
photo[i] = new FlickerImages(photoSet.MediumURLS[i], photoSet.ThumbnailURLS[i], photoSet.Titles[i], photoSet.Descreption[i], photoSet.PhotosID[i]);
panel = photo[i].GetPanelWithEditControls(i);
button = new Button();
button.ID = "sendDataButton" + i;
button.Text = "send data";
button.Click += button_Click;
panel.Controls.Add(button);
Form.Controls.Add(panel);
}
}
}
(sorry for my english)
Instead of putting your control generation in Page_Load, put it in Page_Init.
Since you mentioned that you're pretty new to ASP.NET, I strongly recommend reading up on the Page Lifecycle.
As an ASP.NET developer, it's very important that you understand how and when certain things happen on the server in between the time the server receives a request for an aspx page, and the time the page is output to be rendered by the browser.
The short explanation for why I suggest putting the code in Page_Init is how the runtime deals with dynamically created controls and Viewstate. The Viewstate contains any changes made by the user of your web app. In the page lifecycle, you'll notice that the application of Viewstate values happen before Page_Load, but after Page_Init.
This means that if your code in in Page_Load, then the controls are generated from Viewstate, updated with what the user put in, but then your own code in page_Load is re-generating those controls with the default values. There's nothing that happens after this event that can re-load the user's input.
(Hopefully that makes sense. If not, the page I linked to may explain it better.)
There's another article on here that addresses the subject from a different angle, but still should be very helpful for you.
And there's the ultra-short version here.
And finally, (saving the best for last) one of the most comprehensive articles on the subject that explains things in plain English can be found here.

FindName returning null

I'm writing a simple tic tac toe game for school. The assignment is in C++, but the teacher has given me permission to use C# and WPF as a challenge. I've gotten all the game logic finished and the form mostly complete, but I've run into a wall. I'm currently using a Label to indicate who's turn it is, and I want to change it when a player makes a valid move. According to Applications = Code + Markup, I should be able to use the FindName method of the Window class. However, it keeps returning null. Here's the code:
public TicTacToeGame()
{
Title = "TicTacToe";
SizeToContent = SizeToContent.WidthAndHeight;
ResizeMode = ResizeMode.NoResize;
UniformGrid playingField = new UniformGrid();
playingField.Width = 300;
playingField.Height = 300;
playingField.Margin = new Thickness(20);
Label statusDisplay = new Label();
statusDisplay.Content = "X goes first";
statusDisplay.FontSize = 24;
statusDisplay.Name = "StatusDisplay"; // This is the name of the control
statusDisplay.HorizontalAlignment = HorizontalAlignment.Center;
statusDisplay.Margin = new Thickness(20);
StackPanel layout = new StackPanel();
layout.Children.Add(playingField);
layout.Children.Add(statusDisplay);
Content = layout;
for (int i = 0; i < 9; i++)
{
Button currentButton = new Button();
currentButton.Name = "Space" + i.ToString();
currentButton.FontSize = 32;
currentButton.Click += OnPlayLocationClick;
playingField.Children.Add(currentButton);
}
game = new TicTacToe.GameCore();
}
void OnPlayLocationClick(object sender, RoutedEventArgs args)
{
Button clickedButton = args.Source as Button;
int iButtonNumber = Int32.Parse(clickedButton.Name.Substring(5,1));
int iXPosition = iButtonNumber % 3,
iYPosition = iButtonNumber / 3;
if (game.MoveIsValid(iXPosition, iYPosition) &&
game.Status() == TicTacToe.GameCore.GameStatus.StillGoing)
{
clickedButton.Content =
game.getCurrentPlayer() == TicTacToe.GameCore.Player.X ? "X" : "O";
game.MakeMoveAndChangeTurns(iXPosition, iYPosition);
// And this is where I'm getting it so I can use it.
Label statusDisplay = FindName("StatusDisplay") as Label;
statusDisplay.Content = "It is " +
(game.getCurrentPlayer() == TicTacToe.GameCore.Player.X ? "X" : "O") +
"'s turn";
}
}
What's going on here? I'm using the same name in both places, but FindName can't find it. I've tried using Snoop to see the hierarchy, but the form doesn't show up in the list of applications to choose from. I searched on StackOverflow and found I should be able to use VisualTreeHelper class, but I don't understand how to use it.
Any ideas?
FindName operates on the XAML namescope of the calling control. In your case, since the control is created entirely within code, that XAML namescope is empty -- and that's why FindName fails. See this page:
Any additions to the element tree after initial loading and processing must call the appropriate implementation of RegisterName for the class that defines the XAML namescope. Otherwise, the added object cannot be referenced by name through methods such as FindName. Merely setting a Name property (or x:Name Attribute) does not register that name into any XAML namescope.
The easiest way to fix your problem is to store a reference to your StatusDisplay label in the class as a private member. Or, if you want to learn how to use the VisualTreeHelper class, there's a code snippet at the bottom of this page that walks the visual tree to find the matching element.
(Edited: Of course, it's less work to call RegisterName than to use the VisualTreeHelper, if you don't want to store a reference to the label.)
I'd recommend reading the first link in its entirety if you plan on using WPF/Silverlight in any depth. Useful information to have.
You have to create a new NameScope for your window:
NameScope.SetNameScope(this, new NameScope());
Then you register name of your label with the window:
RegisterName(statusDisplay.Name, statusDisplay);
So this seems to be all you need to do to make FindName() work.

Categories

Resources