Can I programmatically change styles.xml in Xamarin.Forms?

旧巷老猫 提交于 2021-02-07 06:14:29

问题


We have an app that has customizable colors. This makes the orange Android default for selected items in a list view look pretty bad sometimes. We want to change the color of a listview's selected item.

I know how to do this in the code behinds (xaml.cs) for our pages and I'm aware you can statically change it in the styles.xml. But because the listview color can change, we could be left with a similar issue with whatever color we pick.

Is there a way to access and change the styles.xml values from code?


回答1:


You can do it with Xamarin Themes has a clear tutorial on how to do it.

Then You can use the following to change themes

void OnPickerSelectionChanged(object sender, EventArgs e)
{
    Picker picker = sender as Picker;
    Theme theme = (Theme)picker.SelectedItem;

    ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries;
    if (mergedDictionaries != null)
    {
        mergedDictionaries.Clear();

        switch (theme)
        {
            case Theme.Dark:
                mergedDictionaries.Add(new DarkTheme());
                break;
            case Theme.Light:
            default:
                mergedDictionaries.Add(new LightTheme());
                break;
        }
    }
}

UPDATE:

If you want to change the selection on android you'll have to do it in your android styles.xml file, to change it dynamically you'll have to write an affect :

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="DarkYellow">#FF00FF</color>
  <style name="Theme.MyHoloLight" parent="android:Theme.Holo.Light">
    <item name="android:colorPressedHighlight">@color/DarkYellow</item>
    <item name="android:colorLongPressedHighlight">@color/DarkYellow</item>
    <item name="android:colorFocusedHighlight">@color/DarkYellow</item>
    <item name="android:colorActivatedHighlight">@color/DarkYellow</item>
    <item name="android:activatedBackgroundIndicator">@color/DarkYellow</item>
  </style>
</resources>



回答2:


We can also create the ViewCell renderer with the Backgroundcolor Bindable property. With that what we can do is to set the required color to the Bindable property into xaml itself and that will set the color in its renderer so we can provide different colors as per requirement.



来源:https://stackoverflow.com/questions/48465053/can-i-programmatically-change-styles-xml-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!