How to reference the name of an object in c#

I have several buttons all using the same 'clicked' event. Each button is in its own Grid along with a StackLayout containing 2 Labels. I want to retrieve the Text from the first Label that is in the StackLayout within the same Grid as the button that was clicked. In my UWP native app I simply reference Button.Name and can determine the Label that way, but that option is not available is Xamarin.Forms. Any ideas?

<Grid Grid.Row="1" Grid.Column="1"> <StackLayout > <Label x:Name="Monday1Label" /> <Label x:Name="Monday1HD" /> </StackLayout> <Button x:Name="Monday1Button" Clicked="calendarDay_Clicked"/> </Grid>

EX: UWP Native App (Works)
private void calendarDay_Clicked(object sender, RoutedEventArgs e) { string _str = ((Button)sender).Name; TextBlock _label = (TextBlock)FindName(_str.Remove(_str.Length - 6) + "Label"); int _int = int.Parse(_label.Text); ...more code }

How can I do this in Xamarin.Forms? Thanks.

Answers

  • YuraBabiyYuraBabiy UAMember ✭✭✭

    I am using commands instead of events, so I don't remember exact names, but what I can suggest you, that you can use ClickedEventArgs(or something like that) or sender, as you did it with UWP, or you can bind Text property with "OneWayToSource" or "TwoWays" option.

  • JohnHardmanJohnHardman GBUniversity mod

    @TrevorTirrell - the direct equivalent of what you are asking for is the AutomationId property. However, I would advise doing what @YuraBabiy suggests above (using Command or binding).

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
    edited November 2016

    The suggestion by @YuraBabiy is good for this situation.

    My suggestion would be to improve upon the situation. Here's what I mean by that... Code duplication is bad and we all know that. The same is true even in XAML markup. Rather than have "several" blocks of these identical Grid/Stack/Label/Button constructs then having to play silly games from code behind to reach backward from the button to get its label sibling then get the text off that... [yuck]... Instead of all that, make a control that you can reuse.

    If you make a ContentView that consists of the entire set of controls you're using, then give it the needed properties such as DisplayText you only need to add 10 instances of your new control... Or better still you could bind to a collection of data and use your new control as the DataTemplate. No more games about the VM having to know explicit information about the UI. Instead your CustomInfoPanel (or whatever you name it) will raise a Tapped command and carry with it all the properties you need such as that piece of text.

    In other words, work in a more Object Oriented way. Since you have a Grid/Stack/Label/Button acting as a single control representing a single data object, code it that way.

Sign In or Register to comment.