Home > Software design >  Can i change/bind HorizontalOptions's value in XAML code with Variable in C# backend code?
Can i change/bind HorizontalOptions's value in XAML code with Variable in C# backend code?

Time:09-17

I have this label in Xamarin form:

<Label HorizontalOptions="Start"/>

But i want the value of HorizontalOptions become changeable bases on my input into a string variable (string getH) in the backend code.

I tried using binding method, but it does not work.

<Label HorizontalOptions="{Binding 
 getH}"/> (XAML code)

getH = "End"; (C# code)

Is there any binding method that could work in this case?

CodePudding user response:

The type of HorizontalOptions is not string and hence you can't bind to a string. Its of type LayoutOptions and you should bind it to a property of type LayoutOptions like below,

public LayoutOptions GetH { get; set; } = LayoutOptions.Center;

and then on the Xaml,

<Label HorizontalOptions="{Binding GetH}" />

or else if you wish to bind to a string for some reason, then you can have a converter. There's already a solution for this here.

CodePudding user response:

Yes, if you want to bind string variabke, you could use converter to achieve this.

I created a simple demo , you can refer to it.

MyViewModel.cs

   public class MyViewModel: INotifyPropertyChanged
    {
        public ICommand BtnResetClickedCommand { private set; get; }
        public MyViewModel() {

            GetH = "End";

            BtnResetClickedCommand = new Command(ResetMethod);
        }

        private void ResetMethod(object obj)
        {
            GetH = "Start";
        }

        string _getH;


        public string GetH
        {
            set { SetProperty(ref _getH, value); }

            get { return _getH; }
        }

        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Object.Equals(storage, value))
                return false;

            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

MyTextAlignmentConverter.cs

   public class MyTextAlignmentConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                string valueAsString = value.ToString();
                switch (valueAsString)
                {
                    case ("EndAndExpand"):
                        {
                            return LayoutOptions.EndAndExpand;
                        }
                    case ("StartAndExpand"):
                        {
                            return LayoutOptions.StartAndExpand;
                        }
                    case ("Center"):
                        {
                            return LayoutOptions.Center;
                        }
                    case ("End"):
                        {
                            return LayoutOptions.End;
                        }
                    case ("Start"):
                        {
                            return LayoutOptions.Start;
                        }
                    default:
                        {
                            return LayoutOptions.StartAndExpand;
                        }
                }
            }
            else
            {
                return LayoutOptions.Center;

            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

Usage:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:testbottomsheet="clr-namespace:TestBottomSheet"
             x:Class="TestBottomSheet.OptionPage">

    <ContentPage.Resources>
        <ResourceDictionary >
            <testbottomsheet:MyTextAlignmentConverter x:Key="mTextAlignmentConverter">
            </testbottomsheet:MyTextAlignmentConverter>
        </ResourceDictionary>

    </ContentPage.Resources>

    <ContentPage.BindingContext>
        <testbottomsheet:MyViewModel></testbottomsheet:MyViewModel>
    </ContentPage.BindingContext>
  
    <ContentPage.Content>
        <StackLayout  HorizontalOptions="FillAndExpand">
            <Label Text="Welcome to Xamarin.Forms!" BackgroundColor="Yellow"  
                VerticalOptions="CenterAndExpand"   HorizontalOptions="{Binding GetH,Converter={StaticResource mTextAlignmentConverter}}"
                />

            <Button Text="reset" Command="{Binding BtnResetClickedCommand}}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Note:

In above code ,I implemented interface INotifyPropertyChanged for viewmodel MyViewModel, and added a reset button.When I click the button, we can also change the binded value for variable GetH and refresh the UI.

  • Related