c# xamarin forms - custom event on custom control with a property - c#

Okay, im positive this has an answer somewhere but I have been banging my head against a wall FOREVER trying to get this to work, an working around it for days, and im losing my mind here. I cannot find a single example that works or does what I want... at least not that I understand how its written.
Im writing a custom control, basically a content view with a calculator in it. One of the controls in this is an entry.
What i want is VERY simple... when you create an entry in XAML you can do
<Entry TextChanged="FunctionToRun">
and then whenever the text is changed, an event is fired and that function is run.
In my case i want to add a custom event to my calculator class so that when i create one on a page:
<local:myCalculator CountUpdated="FunctionToRun">
that function gets run.
Everything I look at online talks about using an ICommand and all this - but literally every single example I have tried leads me to either:
A) Not be able to link my function in XAML (errors)
B) Only calls something inside the calculator class.... but doesnt trigger any events, and i cannot force it to.
I think i completely do not understand ICommand, and no matter how many examples I ahve looked at I cannot get what im after.
Anyone able to help? im sure its stupidly simple...

Turns out I was being completely blind and didnt realize i had implemented my event on the item with:
public EventHandler<EventArgs> EventName = {get;set;}
Which is absolutely not how you do it - I wont rewrite the reasoning when I can just find an existing answer:
event EventHandler vs EventHandler
Why do we need the "event" keyword while defining events?
Anyhow - it was a blank-minded mistake while coding a lot at once. This should be
public event EventHandler<EventArgs> EventName;
for many reasons - one of the most minor being it allows you to bind properly from XAML.

Related

The opposite of events and delegates?

This might sound weird, but I am just experimenting with the thought of it. I was wondering about subscribing functions to different classes. So i have a base or static location where my method is held, and without relying on inheritance, am i able to subscribe that function to an object?
For example:
Action class has a method class SendKeys
I have three objects called Textbox and Button and Textarea
Realistically i don't want them all to have access to SendKeys function, just Textbox, and Textarea. But i also don't want to copy paste the SendKeys code over and over again.
I could create a static class that takes the data and the two objects will call that static class, but that just seems like extra work and i would be creating the function anyways in order to call an external function.
The best solution i have is to just copy paste code. but i was wondering if i could subscribe specific functions. Its like the opposite of what an event and delegate can do right? Cause the subscription requires code in the class of the subscriber. I kind of think i want partial classes? I am not sure. Thoughts?
A deeper dive into the issue:
I have a bunch of different elements to work with here are some basic ones, it goes deeper when you take into account custom elements:
Button
Textbox
Textarea
MultiSelect
SingleSelect
RadioButtons
Checkboxes
MenuItems
PasswordTextboxes
ETC
Each one of these would have their own actions that can be applied. For example they all would have the same properties like GetAttribute or GetCssValue but i don't want to be sending keys to a checkbox, so i dont want to have the ability to have that function when creating inheritance. BUT, i do want other objects to have those functions. The code is lengthy and a bunch of copy pasting code is ugly. I was hoping i can subscribe functnions to objects. So i can say something like Actions.Click(Textbox) or Textbox.Click or w.e but i cannot do Actions.SendKeys(button, "fdsaf") or Button.SendKeys("fdsaf")

C# WPF add KeyUp event for window with a handler in another page

I'm working on a WPF project and I'm new to it. I organize my project like this:
MainWindow.xaml (Contains a NavigationWindow)
MainWindow.xaml.cs
HomePage.xaml (Contains a series of function)
Homepage.xaml.cs
The thing is that I want to add a KeyUp event to my program, and I want it to call a function in HomePage.xaml.cs when a key is pressed. But I found that it is impossible to add a KeyUp event to a Page object, thus I decided to add it for NavigationWindow. However, I cannot reach the function in HomePage.xaml.cs inside NavigationWindow, so I came up with an idea.
var window = Window.GetWindow(this);
((MainWindow) window).KeyUp += new system.Windows.Input.KeyEventHandler(this.Window_KeyUp);
However, this doesn't work and throw a System.NullReferenceException. I don't know why it happens. Maybe it wants to say that this is null in here? But why?
Though it is silly, I would like to answer to this question myself. (BTW, I haven't received many answers which upsets me. Luckily I found the problem)
The problem is about Window.GetWindow(this). It returns null, which clearly doesn't have a KeyUp event. The solution is to change it to Application.Current.Windows, which is an array of windows hierarchy. Thus Application.Current.Windows[0] can return the MainWindow object, which can be attached with the handler.

Casting datacontext to specific type doesn't work and just skips line

In my Windows Phone 8.1 C# application I have a databound ListView in which each item has a button the user can click (defined through the DataTemplate).
On the Click event (wired in xaml) I write the following code:
FrameworkElement element = (FrameworkElement)e.OriginalSource;
if (element.DataContext is SmappeeAPITD.actuator)
{
actuator act = (SmappeeAPITD.actuator)(element.DataContext);
//Do what I want to do :/
}
The program goes inside the if-clause, thus proving that indeed the DataContext is of the correct type (a manual breakpoint also proved this), but once it should cast the program simply goes to the end of the clickhandler method.
Putting a try/catch around it doens't catch a thing, and listening to the App_UnhandledException event in the App itself also results in nothing.
I'm doing something silly wrong, but I just can't find it :/
If you don't have any code happening after the casting, it fairly obvious the code simply skips to the end of the current method.
So all is well in the world and no questions were asked :p
Thanks to use yasen for helping me find my fault

Windows Hub Template App Accessing Textboxes

I am working on a Windows Store Hub App using XAML and C#. I am not proficient in C#. I understand the basics. Please go easy on me. I know you're wondering why I would even attempt this and so am I at this point. I come from a web design background and could have used Javascript. But I have really learned a lot by doing it and googling what I didn't understand. The app controls really made me jump through hoops to do anything I wanted to do which must not be anything anyone else wants to do or there would be more documentation. I should also mention I've never worked very much with forms so I don't have that background either.
I actually do have a question. I am almost finished and on the last hub section. I want to have textboxes that accept user input. This will be for integers and will have a running total. I can write that code albeit primitively. What I can't do is access the textboxes inside the hub. If I try to put them outside the hub I can but then they don't scroll with the page so I have textboxes floating there.
If they weren't in the hub I could just write:
private void Button_Click(object sender, RoutedEventArgs e)
{
int a = Convert.ToInt32(tbOne.Text);
int b = Convert.ToInt32(tbTwo.Text);
int c = a + b;
Total.Text = c.ToString();
}
Of course, it will be more complicated than that but that is the basic idea. Inside the hub, it does not recognize the x:name.
I would appreciate any insight into this or links if anyone has any. I couldn't find anything by searching.
Investigate the MVVM pattern. Accessing all controls by name is not the best way to do this. You want to set the data context of the your Hub to a seperate class that has properties like TextBox1Text and TextBox2Text and that implements INotifyPropertyChanged. Then in XAML bind those to the controls like . This will give you access to those controls nested in the Hub.

Event Handler located in different class than MainWindow

So I followed the guide on the following site to restrict the characters a textbox can accept.
http://www.rhyous.com/2010/06/18/how-to-limit-or-prevent-characters-in-a-textbox-in-csharp/
My problem is I can't figure out how to make the event handler trigger in the secondary class. Basically how do I tell VS to look for the event handler code in that class instead of MainWindow? I tried searching, but apparently don't know the correct terms to use. The xaml reference I used was
xmlns:DigitBox="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"
Any ideas?
Simplest way I've found to do it is assign the event in your constructor.
public MainWindow()
{
InitializeComponent();
TextBoxCurrency.GotFocus += expandedTextBoxEvents.TextBoxCurrencyGotFocus;
TextBoxCurrency.LostFocus += expandedTextBoxEvents.TextBoxCurrencyLostFocus;
}
I've searched a way to do it in XAML and I did not found an easy and clean way to do it.
You are much better off using commands and command bindings. I'm not sure what the specific command that would would bind to for a text box for your desired functionality, but one of the goals for WPF was to lessen the use of Event Handlers in code behind.
Check out this article for an overview of commands and this article for a way to hook up commands with events. WPF commanding is one of the coolest features to enable true separation of concerns between UI and business logic.
As a worst case scenario solution, you could create your own text box that inherits from the text box control and hook up the events in that class. Your control would then be reusable.

Categories

Resources