How to change the background color of a stacklayout based on color choose from a picker?

I have a stacklayout. And I have a picker which contains different color names. If I choose Red, means, It should display stacklayout in red background .....Any Suggestion please...........

Answers

  • Sumit_SharmaSumit_Sharma USMember ✭✭✭

    A dirty way of doing it will be, In Your Picker SelectedIndexChanged event in code behind.

    You can change the Background color of your stack to the Picker Selected Item

    Or you can use ControlTemplate.

  • MonalishaMonalisha Member ✭✭

    Thanks for quick response. Actually I have a add button. After clicking the add button one pop up view appears, there I am writing some texts.And during that time only I am asking user to pick color from picker. And whatever color will be choosed that color should be appear on the background of particular list item

  • yelinzhyelinzh Member, Xamarin Team Xamurai

    The following code can achieve your feature as you expected.
    in MainPage.xaml:

    <StackLayout x:Name="stl">
            <Label Text="MainPage"/>
            <Picker Title="Select BackgroudColor" 
                    SelectedIndexChanged="OnPickerSelectedIndexChanged">
                <Picker.Items>
                    <x:String>Red</x:String>
                    <x:String>Blue</x:String>
                    <x:String>Yellow</x:String>
                </Picker.Items>
            </Picker>
        </StackLayout>
    

    in MainPage.xamlcs:

    void OnPickerSelectedIndexChanged(object sender,EventArgs e) {
                var picker = (Picker)sender;
                var selectedItem = picker.SelectedItem;
                switch ((int)picker.SelectedIndex) {
                    case 0:
                        stl.BackgroundColor = Color.Red;
                        break;
                    case 1:
                        stl.BackgroundColor = Color.Blue;
                        break;
                    case 2:
                        stl.BackgroundColor = Color.Yellow;
                        break;
                    default:
                        stl.BackgroundColor = Color.White;
                        break;
                }
            }
    
  • yelinzhyelinzh Member, Xamarin Team Xamurai
    edited March 8

    @Monalisha Does the approach work well?

Sign In or Register to comment.