【发布时间】:2020-08-06 18:45:19
【问题描述】:
我在 Xamarin 中创建了一个 Master-Detail 类型的项目。当我从母版页中选择一个项目时,默认情况下背景颜色为橙色。如何将其更改为我选择的颜色?
【问题讨论】:
-
您可以按照本教程c-sharpcorner.com/article/…更改列表视图的选中项颜色
标签: asp.net listview xamarin styles
我在 Xamarin 中创建了一个 Master-Detail 类型的项目。当我从母版页中选择一个项目时,默认情况下背景颜色为橙色。如何将其更改为我选择的颜色?
【问题讨论】:
标签: asp.net listview xamarin styles
可以为ViewCell的ContentView绑定BackgroundColor,然后使用ListView的ViewModel和ItemTapped方法修改选中项的背景颜色。
例如xaml代码如下:
<ListView x:Name="ListViewMenu"
HasUnevenRows="True" ItemTapped="ListViewMenu_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<Grid Padding="10"
BackgroundColor="{Binding SelectedBackgroundColor}">
<Label Text="{Binding Title}" d:Text="{Binding .}" FontSize="20"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
然后在 HomeMenuItem 模型中添加SelectedBackgroundColor 属性:
public enum MenuItemType
{
Browse,
About
}
public class HomeMenuItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MenuItemType Id { get; set; }
public string Title { get; set; }
private Color selectedBackgroundColor;
public Color SelectedBackgroundColor
{
set
{
if (selectedBackgroundColor != value)
{
selectedBackgroundColor = value;
OnPropertyChanged("SelectedBackgroundColor");
}
}
get
{
return selectedBackgroundColor;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后在MenuPage中修改ItemSource如下:
public partial class MenuPage : ContentPage
{
MainPage RootPage { get => Application.Current.MainPage as MainPage; }
List<HomeMenuItem> menuItems;
List<HomeMenuItem> tmpItems; // add a tmp list to remove setted backgroud color
public MenuPage()
{
InitializeComponent();
tmpItems = new List<HomeMenuItem>();
menuItems = new List<HomeMenuItem>
{
new HomeMenuItem {Id = MenuItemType.Browse, Title="Browse" },
new HomeMenuItem {Id = MenuItemType.About, Title="About" }
};
menuItems[0].SelectedBackgroundColor = Color.Red; // default set the first item be selected, you can modify as your wants
tmpItems.Add(menuItems[0]); // add the selected item (default is the first)
ListViewMenu.ItemsSource = menuItems;
ListViewMenu.SelectedItem = menuItems[0];
ListViewMenu.ItemSelected += async (sender, e) =>
{
if (e.SelectedItem == null)
return;
var id = (int)((HomeMenuItem)e.SelectedItem).Id;
await RootPage.NavigateFromMenu(id);
};
}
private void ListViewMenu_ItemTapped(object sender, ItemTappedEventArgs e)
{
menuItems[e.ItemIndex].SelectedBackgroundColor = Color.Red;
tmpItems[0].SelectedBackgroundColor = Color.Transparent;
tmpItems[0] = menuItems[e.ItemIndex];
}
}
效果:
【讨论】:
此问题是 Android 特有的。在 Android 项目中,将此行添加到 <style> 标记内的 Resources\values\styles.xml:
<item name="android:colorActivatedHighlight">#00FFFFFF</item>
【讨论】: