我有使用自定义模板的列表视图。如何突出显示所选内容 不使用代码隐藏的项或选项卡式项?
视图
<StackLayout
Grid.Row="1"
BackgroundColor="#21576C"
HorizontalOptions="StartAndExpand"
VerticalOptions="StartAndExpand">
<StackLayout
BackgroundColor="#134359"
Margin="5,5,5,5">
<ListView x:Name="Catagoris"
HorizontalOptions="Start"
VerticalOptions="FillAndExpand"
BackgroundColor="Transparent"
HasUnevenRows="True"
ItemsSource="{Binding CatagoryType}"
ItemSelected="ListView_OnItemSelected"
MinimumHeightRequest="100"
SeparatorVisibility="None"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label x:Name="ListViewLabel"
HorizontalOptions="FillAndExpand"
HorizontalTextAlignment="Center"
VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center"
TextColor="#3C9DC5"
Text="{Binding ., Converter={StaticResource SpaceOnUpperAndStringToUpperCaseConverter}}"
HeightRequest="50">
</Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
虚拟机中的道具
public bool IsCatagorySelected
{
get { return _isCatagorySelected; }
set
{
if (_isCatagorySelected != value)
{
OnPropertyChanging(()=>IsCatagorySelected);
_isCatagorySelected = value;
OnPropertyChanged(() => IsCatagorySelected);
}
}
}
代码隐藏
private void ListView_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
MyViewModel myViewModel= sender as MyViewModel;
if (e.SelectedItem == null)
{
return;
}
myViewModel.IsCatagorySelected= true;
DisplayAlert("Item Selected", e.SelectedItem.ToString(), "OK");
}
我需要更改标签"列表视图标签"的背景颜色和文本颜色。
我建议看看这个博客
您应该将"已选择"属性添加到模型中
public bool Selected { get; set; }
在视图模型中,您应该有一个属性,用于定义列表视图中的选定项
MyModel _selectedItem { get; set; }
并以这种方式使用它
public MyModel SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != null)
_selectedItem.Selected = false;
_selectedItem = value;
if (_selectedItem != null)
_selectedItem.Selected = true;
}
}
然后在 XAML 中,必须绑定列表视图的选定项和文本颜色属性
<ListView SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding List}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Name}" TextColor="{Binding Selected, Converter={StaticResource cnvInvert}}}" FontSize="18"></Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
属性具有一个 IValueConverter,该转换器将 Selected 属性转换为 Color 属性
public class SelectedToColorConverter : IValueConverter
{
#region IValueConverter implementation
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
if ((Boolean)value)
return Color.Orange;
else
return Color.Black;
}
return Color.Black;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
在博客中有一个指向 GitHub 上的 REPO 的链接