How to access Picker.Focus() from a view-model of a xaml page?

EB1234EB1234 USMember

I have a picker which presents some values to chose from. and I read online that to open this picker from a button click I have to use .Focus(). But the problem is it seems that .Focus() is accessible just from the XAML.cs file. How I can assess it from its view model class?

Best Answer

Answers

  • NMackayNMackay GBInsider, University mod

    Another approach is to use behaviors to listen for a property change in the viewmodel and set the picker focus.

    I discuss this approach here.

    https://forums.xamarin.com/discussion/86315/how-to-get-the-viewmodel-to-communicate-to-the-views-code-behind-file

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @NMackay said:
    Another approach is to use behaviors to listen for a property change in the viewmodel and set the picker focus.
    I discuss this approach here.
    https://forums.xamarin.com/discussion/86315/how-to-get-the-viewmodel-to-communicate-to-the-views-code-behind-file

    Read it... Nice post... clear explanation and good example of why it is so important to keep View layer and ViewModel code separated.

  • hamid_shaikhhamid_shaikh Member ✭✭

    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

          public DelegateCommand<Picker> ActivePickerCommand => new DelegateCommand<Picker>((Picker picker) => { picker.Focus(); });
    

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    
  • hamid_shaikhhamid_shaikh Member ✭✭

    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

          public DelegateCommand<Picker> ActivePickerCommand => new DelegateCommand<Picker>((Picker picker) => { picker.Focus(); });
    

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    
  • saishaiksaishaik INMember ✭✭

    Hi @hamid_shaikh , I am trying your solution, but can you explain me how DelegateCommand can be assigned as it is throwing an error while defining it in my viewmodel.

  • NMackayNMackay GBInsider, University mod
    edited January 15

    @hamid_shaikh said:
    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

        public DelegateCommand<Picker> ActivePickerCommand => new DelegateCommand<Picker>((Picker picker) => { picker.Focus(); });
    

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
                    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    

    That is a complete and utter violation of the MVVM pattern if your passing a UI control to the viewmodel to be manipulated :o :'( :# Do NOT do this, use EventToCommand to handle business logic in the viewmodel or if it's UI specific handle it in code behind.

  • hamid_shaikhhamid_shaikh Member ✭✭

    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

    public DelegateCommand ActivePickerCommand => new DelegateCommand((Picker picker) => { picker.Focus(); });

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    

    @saishaik said:
    Hi @hamid_shaikh , I am trying your solution, but can you explain me how DelegateCommand can be assigned as it is throwing an error while defining it in my viewmodel.

    @saishaik
    DelegateCommand is part of Prism.Forms Libraray/Framework. If you are not using Prism.Forms then use like below

    public Command ActivePickerCommand => new Command((Picker picker) => { picker.Focus(); });

  • NMackayNMackay GBInsider, University mod

    @hamid_shaikh said:
    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

    public DelegateCommand ActivePickerCommand => new DelegateCommand((Picker picker) => { picker.Focus(); });

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
                    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    

    @saishaik said:
    Hi @hamid_shaikh , I am trying your solution, but can you explain me how DelegateCommand can be assigned as it is throwing an error while defining it in my viewmodel.

    @saishaik
    DelegateCommand is part of Prism.Forms Libraray/Framework. If you are not using Prism.Forms then use like below

    public Command ActivePickerCommand => new Command((Picker picker) => { picker.Focus(); });

    This is still completely wrong for all the reasons listed in this thread :s

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @NMackay said:
    This is still completely wrong for all the reasons listed in this thread :s

    Let it go. Either they don't care about it being wrong, or don't grasp the reasons why they'd want to do it right.

    Its all a learning experience. Some of the best lessons learned are from going down the wrong path... getting painted into a corner... then having that ah ha! experience where you say to yourself...

    Oh, now I get what they were talking about and why that leads to problems and doing 10x as much work.

    But until someone experiences it, you can't tell them. Like sex, no amount of talk is going to make someone else fully grok what you're talking about. It has to be experienced.

  • hamid_shaikhhamid_shaikh Member ✭✭

    @NMackay said:

    @hamid_shaikh said:
    You can easily pass your picker control as command parameter...Below is how you can achieve it

    ViewModel code

    public DelegateCommand ActivePickerCommand => new DelegateCommand((Picker picker) => { picker.Focus(); });

    Xaml code

                   <Picker
                        x:Name="pickerControl"
                        ItemsSource="{Binding PickerSource}"
                        ItemDisplayBinding="{Binding DisplayText}"
                        SelectedItem="{Binding SelectedPickerValue}"
                        HorizontalOptions="FillAndExpand"
                        iOSSpecific:Picker.UpdateMode="WhenFinished"
                        TextColor="{StaticResource BlueTextColor}"/>
                    
                    <localsControl:ImageButton
                        HeightRequest="30"
                        WidthRequest="30"
                        Command="{Binding ActivePickerCommand}"
                        CommandParameter="{x:Reference pickerControl}"
                        HorizontalOptions="End"
                        Source="arrow_down.png"
                        x:Name="imgDatePicker"/>
    

    @saishaik said:
    Hi @hamid_shaikh , I am trying your solution, but can you explain me how DelegateCommand can be assigned as it is throwing an error while defining it in my viewmodel.

    @saishaik
    DelegateCommand is part of Prism.Forms Libraray/Framework. If you are not using Prism.Forms then use like below

    public Command ActivePickerCommand => new Command((Picker picker) => { picker.Focus(); });

    This is still completely wrong for all the reasons listed in this thread :s

    @NMackay
    I do understand manipulating UI control from ViewModel is not good practice. My intension is to just provide possible way to pass control to ViewModel.

    So that incase you have defined your control inside ListView where you cannot get access of your control in code behind then you can simply use above sample solution to achieve your requirement.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
    edited January 15

    @hamid_shaikh said:
    I do understand manipulating UI control from ViewModel is not good practice. My intension is to just provide possible way to pass control to ViewModel.

    So you know its bad practice but you're suggesting others should do it, anyway?

    So that incase you have defined your control inside ListView where you cannot get access of your control in code behind then you can simply use above sample solution to achieve your requirement.

    You're not supposed to do that sort of junk. That's the point. You are suggesting really bad things... KNOWING they are really bad things. Why would you do that? Why would you deliberatley mislead people into doing really bad things? Are you trying to make life hard on them? Are you trying to teach them bad practices on purpose? What the heck man? Personally if it were in my power I'd ban you for doing that sort of stuff to others.

  • hamid_shaikhhamid_shaikh Member ✭✭
    edited January 15

    @ClintStLaurent said:

    @hamid_shaikh said:
    I do understand manipulating UI control from ViewModel is not good practice. My intension is to just provide possible way to pass control to ViewModel.

    So you know its bad practice but you're suggesting others should do it, anyway?

    Brother please try to understand that my intention is not to promote any bad practice.

    So that incase you have defined your control inside ListView where you cannot get access of your control in code behind then you can simply use above sample solution to achieve your requirement.

    You're not supposed to do that sort of junk. That's the point. You are suggesting really bad things... KNOWING they are really bad things. Why would you do that? Why would you deliberatley mislead people into doing really bad things? Are you trying to make life hard on them? Are you trying to teach them bad practices on purpose? What the heck man? Personally if it were in my power I'd ban you for doing that sort of stuff to others.

    I would request you to please help us with best practice to overcome with scenario i have explained above. So that others and including me can avoid such bad practice in future.

    @ClintStLaurent Please help

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Dude... There are mountains of books on proper practice. Tons of videos and blogs and tutorials on MVVM.
    There is no way someone can relate what amounts to dozens of hours of course material in one thread.
    You have to take responsibility for your education and learn first - before you try to write code or architect a solution.

    I've put that in literally 100 or more threads here alone. I'm sure I'm not the first person to tell you that "learn as you bang on the keyboard" is not a good learning strategy.

    Here is the same recommendations I post many times for new developers:

    Ok. Then what you're trying to do is far too much for a first app.
    You have to start with building a bird house... then a dog house... then an outhouse... shed... garage...
    Before you try to build a 3 story apartment building.

    If you have no experience with MVVM design... no experience with databinding code to UI... etc. etc. then you need to first get a handle on that.

    Start with working the free textbook from cover to cover.
    https://blogs.msdn.microsoft.com/microsoft_press/2016/03/31/free-ebook-creating-mobile-apps-with-xamarin-forms/

    Feel free to hit up on-line tutorials sites. There are plenty. Here's mine:

    Then just tackle one of those issues at a time in a "Sandbox" or R&D app. Learn each of your bullet points one at a time in a little R&D app before you try to take on putting them all together. You need to understand them as a single thing before you can architect how they will interact.

    But again... 90% of everything you've described has nothing to do with Xamarin. Its all basic-to-intermediate application needs and design that would be the same in Xamarin, WinForms, WPF, Android, ...

    So many noobies take this "no time to study, I have to bang this out now and learn as I go" direction - and it rarely works out well.

    Stop working on this project for at least a couple weeks to a month. Just work on learning. WORK some tutorials from start to end. Build the sample apps the authors are walking you through. Then dissect those apps to gain real comprehension of all the relationships and moving parts. Then take that new understanding and start version two of this app from scratch.

    Free textbook
    https://blogs.msdn.microsoft.com/microsoft_press/2016/03/31/free-ebook-creating-mobile-apps-with-xamarin-forms/

    Xamarin University (for now)
    https://university.xamarin.com/
    Xamarin University has dozens of tutorial classes on YouTube if you use their search feature. Xamarin University is going to soon be totally free as soon as they finish wrapping it into Microsoft Learn.

  • hamid_shaikhhamid_shaikh Member ✭✭

    @ClintStLaurent said:
    Dude... There are mountains of books on proper practice. Tons of videos and blogs and tutorials on MVVM.
    There is no way someone can relate what amounts to dozens of hours of course material in one thread.
    You have to take responsibility for your education and learn first - before you try to write code or architect a solution.

    I've put that in literally 100 or more threads here alone. I'm sure I'm not the first person to tell you that "learn as you bang on the keyboard" is not a good learning strategy.

    Here is the same recommendations I post many times for new developers:

    Ok. Then what you're trying to do is far too much for a first app.
    You have to start with building a bird house... then a dog house... then an outhouse... shed... garage...
    Before you try to build a 3 story apartment building.

    If you have no experience with MVVM design... no experience with databinding code to UI... etc. etc. then you need to first get a handle on that.

    Start with working the free textbook from cover to cover.
    https://blogs.msdn.microsoft.com/microsoft_press/2016/03/31/free-ebook-creating-mobile-apps-with-xamarin-forms/

    Feel free to hit up on-line tutorials sites. There are plenty. Here's mine:

    Then just tackle one of those issues at a time in a "Sandbox" or R&D app. Learn each of your bullet points one at a time in a little R&D app before you try to take on putting them all together. You need to understand them as a single thing before you can architect how they will interact.

    But again... 90% of everything you've described has nothing to do with Xamarin. Its all basic-to-intermediate application needs and design that would be the same in Xamarin, WinForms, WPF, Android, ...

    So many noobies take this "no time to study, I have to bang this out now and learn as I go" direction - and it rarely works out well.

    Stop working on this project for at least a couple weeks to a month. Just work on learning. WORK some tutorials from start to end. Build the sample apps the authors are walking you through. Then dissect those apps to gain real comprehension of all the relationships and moving parts. Then take that new understanding and start version two of this app from scratch.

    Free textbook
    https://blogs.msdn.microsoft.com/microsoft_press/2016/03/31/free-ebook-creating-mobile-apps-with-xamarin-forms/

    Xamarin University (for now)
    https://university.xamarin.com/
    Xamarin University has dozens of tutorial classes on YouTube if you use their search feature. Xamarin University is going to soon be totally free as soon as they finish wrapping it into Microsoft Learn.

    Thanks a lot for sharing details...surely will go through it.

Sign In or Register to comment.