Binding to MvxSpinner SelectedItem property not working











up vote
2
down vote

favorite












I use a MvxSpinner to show country phone prefixes in a combobox in a MvvmCross for Xamarin app. I can bind to the ItemsSource property correctly, so I can see the list of my prefixes but when I assign the property in my view model that is bind to the SelectedItem property of the MvxSpinner, it won't work and will always show the first element in the list as the selected item.



The way I do it is the following. In my ViewModel I get the user data from the server and assign the properties for Country and PhonePrefix. Then I get the list of all countries and prefixes also from server and bind them to the list properties that are binded to the ItemSource properties of the respewctive MvxSpinners (simplified):



    public string PhonePrefix { get; set; }
public string PhoneNumber { get; set; }

public List<Country> Countries { get; set; } = new List<Country>();
public List<string> Prefixes { get; set; } = new List<string>();

private async Task GetUserData()
{
try
{
var userDataResult = await _registrationService.GetLoggedInUserData();

if (userDataResult != null)
{
if (!userDataResult.HTTPStatusCode.Equals(HttpStatusCode.OK))
{
Mvx.IoCProvider.Resolve<IUserDialogs>().Alert(userDataResult.Error?.Message);
}
else
{

PhonePrefix = userDataResult.user.country_code_phone;
PhoneNumber = userDataResult.user.phone;
}
}
}
catch (Exception e)
{
Log.Error<RegistrationViewModel>("GetUserData", e);
}
}

/// <summary>
/// Populates the view model properties for Countries and Prefixes with information retrieved from the server
/// </summary>
private void ProcessFormData()
{
if (_registrationFormData != null)
{
Countries = _registrationFormData.Countries?.ToList();
var userCountry = Countries?.Where(c => c.id == Country?.id).FirstOrDefault();
Country = IsUserLogedIn && Country != null ? userCountry : Countries?[0];

var prefixes = new List<string>();
if (Countries != null)
{
foreach (var country in Countries)
{
//spinner binding doesn't allow null values
if (country.phone_prefix != null)
{
prefixes.Add(country.phone_prefix);
}
}
}

//we need to assign the binded Prefixes at once otherwise the binding for the ItemSource fails
Prefixes = prefixes;
PhonePrefix = Prefixes.Count > 0 && !IsUserLogedIn && string.IsNullOrWhiteSpace(PhonePrefix) ? Prefixes?[0] : PhonePrefix;
}
}


And in the axml layout:



    <MvxSpinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="25dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
android:id="@+id/spnrCountry"
local:MvxBind="ItemsSource Countries; SelectedItem Country"/>
<MvxSpinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="25dp"
android:layout_marginBottom="10dp"
android:id="@+id/spnrPrefix"
local:MvxBind="ItemsSource Prefixes; SelectedItem PhonePrefix"/>


On the output window I can see the following error regarding MvxBinding:



(MvxBind) Null values not permitted in spinner SelectedItem binding currently


I debugged and I never have any Null values in the lists or in the properties I bind to the ItemSource and SelectedItem properties of the MvxSpinner.



Actually the Countries ItemSource and SelectedItem work properly so if user saved it's country to be Argentina, when I load it's data the selected item in the spinner will be Argentina. Note that I use a Country entity like that:



public class Country
{
public int id { get; set; }
public bool favorite { get; set; }
public string name { get; set; }
public string name_de { get; set; }
public string code { get; set; }
public int rzl_code { get; set; }
public string phone_prefix { get; set; }
public string updated_at { get; set; }
public string created_at { get; set; }

public override string ToString()
{
return name;
}
}


I also tried to make the phone prefix in it's own entity wrapping a string value but it didn't work either.



Does anybody knows what I'm doing wrong? Why for the Countries it's working and for the prefixes not?



Thanks!










share|improve this question




























    up vote
    2
    down vote

    favorite












    I use a MvxSpinner to show country phone prefixes in a combobox in a MvvmCross for Xamarin app. I can bind to the ItemsSource property correctly, so I can see the list of my prefixes but when I assign the property in my view model that is bind to the SelectedItem property of the MvxSpinner, it won't work and will always show the first element in the list as the selected item.



    The way I do it is the following. In my ViewModel I get the user data from the server and assign the properties for Country and PhonePrefix. Then I get the list of all countries and prefixes also from server and bind them to the list properties that are binded to the ItemSource properties of the respewctive MvxSpinners (simplified):



        public string PhonePrefix { get; set; }
    public string PhoneNumber { get; set; }

    public List<Country> Countries { get; set; } = new List<Country>();
    public List<string> Prefixes { get; set; } = new List<string>();

    private async Task GetUserData()
    {
    try
    {
    var userDataResult = await _registrationService.GetLoggedInUserData();

    if (userDataResult != null)
    {
    if (!userDataResult.HTTPStatusCode.Equals(HttpStatusCode.OK))
    {
    Mvx.IoCProvider.Resolve<IUserDialogs>().Alert(userDataResult.Error?.Message);
    }
    else
    {

    PhonePrefix = userDataResult.user.country_code_phone;
    PhoneNumber = userDataResult.user.phone;
    }
    }
    }
    catch (Exception e)
    {
    Log.Error<RegistrationViewModel>("GetUserData", e);
    }
    }

    /// <summary>
    /// Populates the view model properties for Countries and Prefixes with information retrieved from the server
    /// </summary>
    private void ProcessFormData()
    {
    if (_registrationFormData != null)
    {
    Countries = _registrationFormData.Countries?.ToList();
    var userCountry = Countries?.Where(c => c.id == Country?.id).FirstOrDefault();
    Country = IsUserLogedIn && Country != null ? userCountry : Countries?[0];

    var prefixes = new List<string>();
    if (Countries != null)
    {
    foreach (var country in Countries)
    {
    //spinner binding doesn't allow null values
    if (country.phone_prefix != null)
    {
    prefixes.Add(country.phone_prefix);
    }
    }
    }

    //we need to assign the binded Prefixes at once otherwise the binding for the ItemSource fails
    Prefixes = prefixes;
    PhonePrefix = Prefixes.Count > 0 && !IsUserLogedIn && string.IsNullOrWhiteSpace(PhonePrefix) ? Prefixes?[0] : PhonePrefix;
    }
    }


    And in the axml layout:



        <MvxSpinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="25dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/spnrCountry"
    local:MvxBind="ItemsSource Countries; SelectedItem Country"/>
    <MvxSpinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="25dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/spnrPrefix"
    local:MvxBind="ItemsSource Prefixes; SelectedItem PhonePrefix"/>


    On the output window I can see the following error regarding MvxBinding:



    (MvxBind) Null values not permitted in spinner SelectedItem binding currently


    I debugged and I never have any Null values in the lists or in the properties I bind to the ItemSource and SelectedItem properties of the MvxSpinner.



    Actually the Countries ItemSource and SelectedItem work properly so if user saved it's country to be Argentina, when I load it's data the selected item in the spinner will be Argentina. Note that I use a Country entity like that:



    public class Country
    {
    public int id { get; set; }
    public bool favorite { get; set; }
    public string name { get; set; }
    public string name_de { get; set; }
    public string code { get; set; }
    public int rzl_code { get; set; }
    public string phone_prefix { get; set; }
    public string updated_at { get; set; }
    public string created_at { get; set; }

    public override string ToString()
    {
    return name;
    }
    }


    I also tried to make the phone prefix in it's own entity wrapping a string value but it didn't work either.



    Does anybody knows what I'm doing wrong? Why for the Countries it's working and for the prefixes not?



    Thanks!










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I use a MvxSpinner to show country phone prefixes in a combobox in a MvvmCross for Xamarin app. I can bind to the ItemsSource property correctly, so I can see the list of my prefixes but when I assign the property in my view model that is bind to the SelectedItem property of the MvxSpinner, it won't work and will always show the first element in the list as the selected item.



      The way I do it is the following. In my ViewModel I get the user data from the server and assign the properties for Country and PhonePrefix. Then I get the list of all countries and prefixes also from server and bind them to the list properties that are binded to the ItemSource properties of the respewctive MvxSpinners (simplified):



          public string PhonePrefix { get; set; }
      public string PhoneNumber { get; set; }

      public List<Country> Countries { get; set; } = new List<Country>();
      public List<string> Prefixes { get; set; } = new List<string>();

      private async Task GetUserData()
      {
      try
      {
      var userDataResult = await _registrationService.GetLoggedInUserData();

      if (userDataResult != null)
      {
      if (!userDataResult.HTTPStatusCode.Equals(HttpStatusCode.OK))
      {
      Mvx.IoCProvider.Resolve<IUserDialogs>().Alert(userDataResult.Error?.Message);
      }
      else
      {

      PhonePrefix = userDataResult.user.country_code_phone;
      PhoneNumber = userDataResult.user.phone;
      }
      }
      }
      catch (Exception e)
      {
      Log.Error<RegistrationViewModel>("GetUserData", e);
      }
      }

      /// <summary>
      /// Populates the view model properties for Countries and Prefixes with information retrieved from the server
      /// </summary>
      private void ProcessFormData()
      {
      if (_registrationFormData != null)
      {
      Countries = _registrationFormData.Countries?.ToList();
      var userCountry = Countries?.Where(c => c.id == Country?.id).FirstOrDefault();
      Country = IsUserLogedIn && Country != null ? userCountry : Countries?[0];

      var prefixes = new List<string>();
      if (Countries != null)
      {
      foreach (var country in Countries)
      {
      //spinner binding doesn't allow null values
      if (country.phone_prefix != null)
      {
      prefixes.Add(country.phone_prefix);
      }
      }
      }

      //we need to assign the binded Prefixes at once otherwise the binding for the ItemSource fails
      Prefixes = prefixes;
      PhonePrefix = Prefixes.Count > 0 && !IsUserLogedIn && string.IsNullOrWhiteSpace(PhonePrefix) ? Prefixes?[0] : PhonePrefix;
      }
      }


      And in the axml layout:



          <MvxSpinner
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:minHeight="25dp"
      android:layout_marginTop="5dp"
      android:layout_marginBottom="10dp"
      android:id="@+id/spnrCountry"
      local:MvxBind="ItemsSource Countries; SelectedItem Country"/>
      <MvxSpinner
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:minHeight="25dp"
      android:layout_marginBottom="10dp"
      android:id="@+id/spnrPrefix"
      local:MvxBind="ItemsSource Prefixes; SelectedItem PhonePrefix"/>


      On the output window I can see the following error regarding MvxBinding:



      (MvxBind) Null values not permitted in spinner SelectedItem binding currently


      I debugged and I never have any Null values in the lists or in the properties I bind to the ItemSource and SelectedItem properties of the MvxSpinner.



      Actually the Countries ItemSource and SelectedItem work properly so if user saved it's country to be Argentina, when I load it's data the selected item in the spinner will be Argentina. Note that I use a Country entity like that:



      public class Country
      {
      public int id { get; set; }
      public bool favorite { get; set; }
      public string name { get; set; }
      public string name_de { get; set; }
      public string code { get; set; }
      public int rzl_code { get; set; }
      public string phone_prefix { get; set; }
      public string updated_at { get; set; }
      public string created_at { get; set; }

      public override string ToString()
      {
      return name;
      }
      }


      I also tried to make the phone prefix in it's own entity wrapping a string value but it didn't work either.



      Does anybody knows what I'm doing wrong? Why for the Countries it's working and for the prefixes not?



      Thanks!










      share|improve this question















      I use a MvxSpinner to show country phone prefixes in a combobox in a MvvmCross for Xamarin app. I can bind to the ItemsSource property correctly, so I can see the list of my prefixes but when I assign the property in my view model that is bind to the SelectedItem property of the MvxSpinner, it won't work and will always show the first element in the list as the selected item.



      The way I do it is the following. In my ViewModel I get the user data from the server and assign the properties for Country and PhonePrefix. Then I get the list of all countries and prefixes also from server and bind them to the list properties that are binded to the ItemSource properties of the respewctive MvxSpinners (simplified):



          public string PhonePrefix { get; set; }
      public string PhoneNumber { get; set; }

      public List<Country> Countries { get; set; } = new List<Country>();
      public List<string> Prefixes { get; set; } = new List<string>();

      private async Task GetUserData()
      {
      try
      {
      var userDataResult = await _registrationService.GetLoggedInUserData();

      if (userDataResult != null)
      {
      if (!userDataResult.HTTPStatusCode.Equals(HttpStatusCode.OK))
      {
      Mvx.IoCProvider.Resolve<IUserDialogs>().Alert(userDataResult.Error?.Message);
      }
      else
      {

      PhonePrefix = userDataResult.user.country_code_phone;
      PhoneNumber = userDataResult.user.phone;
      }
      }
      }
      catch (Exception e)
      {
      Log.Error<RegistrationViewModel>("GetUserData", e);
      }
      }

      /// <summary>
      /// Populates the view model properties for Countries and Prefixes with information retrieved from the server
      /// </summary>
      private void ProcessFormData()
      {
      if (_registrationFormData != null)
      {
      Countries = _registrationFormData.Countries?.ToList();
      var userCountry = Countries?.Where(c => c.id == Country?.id).FirstOrDefault();
      Country = IsUserLogedIn && Country != null ? userCountry : Countries?[0];

      var prefixes = new List<string>();
      if (Countries != null)
      {
      foreach (var country in Countries)
      {
      //spinner binding doesn't allow null values
      if (country.phone_prefix != null)
      {
      prefixes.Add(country.phone_prefix);
      }
      }
      }

      //we need to assign the binded Prefixes at once otherwise the binding for the ItemSource fails
      Prefixes = prefixes;
      PhonePrefix = Prefixes.Count > 0 && !IsUserLogedIn && string.IsNullOrWhiteSpace(PhonePrefix) ? Prefixes?[0] : PhonePrefix;
      }
      }


      And in the axml layout:



          <MvxSpinner
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:minHeight="25dp"
      android:layout_marginTop="5dp"
      android:layout_marginBottom="10dp"
      android:id="@+id/spnrCountry"
      local:MvxBind="ItemsSource Countries; SelectedItem Country"/>
      <MvxSpinner
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:minHeight="25dp"
      android:layout_marginBottom="10dp"
      android:id="@+id/spnrPrefix"
      local:MvxBind="ItemsSource Prefixes; SelectedItem PhonePrefix"/>


      On the output window I can see the following error regarding MvxBinding:



      (MvxBind) Null values not permitted in spinner SelectedItem binding currently


      I debugged and I never have any Null values in the lists or in the properties I bind to the ItemSource and SelectedItem properties of the MvxSpinner.



      Actually the Countries ItemSource and SelectedItem work properly so if user saved it's country to be Argentina, when I load it's data the selected item in the spinner will be Argentina. Note that I use a Country entity like that:



      public class Country
      {
      public int id { get; set; }
      public bool favorite { get; set; }
      public string name { get; set; }
      public string name_de { get; set; }
      public string code { get; set; }
      public int rzl_code { get; set; }
      public string phone_prefix { get; set; }
      public string updated_at { get; set; }
      public string created_at { get; set; }

      public override string ToString()
      {
      return name;
      }
      }


      I also tried to make the phone prefix in it's own entity wrapping a string value but it didn't work either.



      Does anybody knows what I'm doing wrong? Why for the Countries it's working and for the prefixes not?



      Thanks!







      c# mvvmcross selecteditem mvxbind mvxspinner






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      D Manokhin

      590118




      590118










      asked yesterday









      jcasas

      578




      578
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          It does work, as PhonePrefix is set in GetUserData, also you should set Country. From your code Country is null, this is why you are getting the first item from the list selected or error also.






          share|improve this answer






























            up vote
            0
            down vote













            The error you are getting about null is because SelectedItem in the spinner does not allow null as a selected item. So if you want to display an empty item one solution is to add another fixed item that has an empty value, i.e. in the case of PhonePrefix you can set string.Empty and add it to the list of PhonePrefixes and in your Country you can set the first one as default or create a stub Country with name None for example and add it to the list of countries.



            Another point to take into account is that when you want to update the view you have to be sure that you are notifying it in the Main Thread. You are trying to update the PhonePrefix in a Task of another thread so the view does not get noticed.



            You should update PhonePrefix by doing:



            this.InvokeOnMainThread(() => PhonePrefix = userDataResult.user.country_code_phone;
            );



            This will take care of doing the set of PhonePrefix directly on the Main thread so your view will be notified correctly.



            HIH






            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














               

              draft saved


              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408601%2fbinding-to-mvxspinner-selecteditem-property-not-working%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote













              It does work, as PhonePrefix is set in GetUserData, also you should set Country. From your code Country is null, this is why you are getting the first item from the list selected or error also.






              share|improve this answer



























                up vote
                0
                down vote













                It does work, as PhonePrefix is set in GetUserData, also you should set Country. From your code Country is null, this is why you are getting the first item from the list selected or error also.






                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  It does work, as PhonePrefix is set in GetUserData, also you should set Country. From your code Country is null, this is why you are getting the first item from the list selected or error also.






                  share|improve this answer














                  It does work, as PhonePrefix is set in GetUserData, also you should set Country. From your code Country is null, this is why you are getting the first item from the list selected or error also.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited yesterday

























                  answered yesterday









                  Nicolae

                  213




                  213
























                      up vote
                      0
                      down vote













                      The error you are getting about null is because SelectedItem in the spinner does not allow null as a selected item. So if you want to display an empty item one solution is to add another fixed item that has an empty value, i.e. in the case of PhonePrefix you can set string.Empty and add it to the list of PhonePrefixes and in your Country you can set the first one as default or create a stub Country with name None for example and add it to the list of countries.



                      Another point to take into account is that when you want to update the view you have to be sure that you are notifying it in the Main Thread. You are trying to update the PhonePrefix in a Task of another thread so the view does not get noticed.



                      You should update PhonePrefix by doing:



                      this.InvokeOnMainThread(() => PhonePrefix = userDataResult.user.country_code_phone;
                      );



                      This will take care of doing the set of PhonePrefix directly on the Main thread so your view will be notified correctly.



                      HIH






                      share|improve this answer

























                        up vote
                        0
                        down vote













                        The error you are getting about null is because SelectedItem in the spinner does not allow null as a selected item. So if you want to display an empty item one solution is to add another fixed item that has an empty value, i.e. in the case of PhonePrefix you can set string.Empty and add it to the list of PhonePrefixes and in your Country you can set the first one as default or create a stub Country with name None for example and add it to the list of countries.



                        Another point to take into account is that when you want to update the view you have to be sure that you are notifying it in the Main Thread. You are trying to update the PhonePrefix in a Task of another thread so the view does not get noticed.



                        You should update PhonePrefix by doing:



                        this.InvokeOnMainThread(() => PhonePrefix = userDataResult.user.country_code_phone;
                        );



                        This will take care of doing the set of PhonePrefix directly on the Main thread so your view will be notified correctly.



                        HIH






                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          The error you are getting about null is because SelectedItem in the spinner does not allow null as a selected item. So if you want to display an empty item one solution is to add another fixed item that has an empty value, i.e. in the case of PhonePrefix you can set string.Empty and add it to the list of PhonePrefixes and in your Country you can set the first one as default or create a stub Country with name None for example and add it to the list of countries.



                          Another point to take into account is that when you want to update the view you have to be sure that you are notifying it in the Main Thread. You are trying to update the PhonePrefix in a Task of another thread so the view does not get noticed.



                          You should update PhonePrefix by doing:



                          this.InvokeOnMainThread(() => PhonePrefix = userDataResult.user.country_code_phone;
                          );



                          This will take care of doing the set of PhonePrefix directly on the Main thread so your view will be notified correctly.



                          HIH






                          share|improve this answer












                          The error you are getting about null is because SelectedItem in the spinner does not allow null as a selected item. So if you want to display an empty item one solution is to add another fixed item that has an empty value, i.e. in the case of PhonePrefix you can set string.Empty and add it to the list of PhonePrefixes and in your Country you can set the first one as default or create a stub Country with name None for example and add it to the list of countries.



                          Another point to take into account is that when you want to update the view you have to be sure that you are notifying it in the Main Thread. You are trying to update the PhonePrefix in a Task of another thread so the view does not get noticed.



                          You should update PhonePrefix by doing:



                          this.InvokeOnMainThread(() => PhonePrefix = userDataResult.user.country_code_phone;
                          );



                          This will take care of doing the set of PhonePrefix directly on the Main thread so your view will be notified correctly.



                          HIH







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered yesterday









                          fmaccaroni

                          2,0951723




                          2,0951723






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408601%2fbinding-to-mvxspinner-selecteditem-property-not-working%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Contact image not getting when fetch all contact list from iPhone by CNContact

                              count number of partitions of a set with n elements into k subsets

                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks