【发布时间】:2018-06-22 02:45:11
【问题描述】:
我正在尝试通过更改所选标签的颜色来控制标签的背景颜色。我遵循 MVVM 模式,我实现的方式是这样的:
在模型中,我创建了一个带有 get 和 set 的布尔值,它必须检测是否选择了我的列表视图中的项目。
public boolean Selected {get; set;}在我看来,我将背景颜色属性绑定到布尔值,并将 IValueConverter 设置为转换器
- 在 ViewModel 中,我实现了 get 和 set
它似乎只检查一次,因为背景颜色总是白色的。我已经在 Converter 中使用断点对其进行了检查,它仅在启动列表时调用,而不是在更新项目时调用。
IValue 转换器:
public class SelectedItemColorConverter : 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.Red;
else
return Color.White;
}
return Color.White;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
这是列表视图:
<StackLayout x:Name="standingsStackLayout" IsVisible="False">
<ListView x:Name="standingsList" SeparatorColor="Black" ItemsSource="{Binding StandingsListSource}" SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label x:Name="TournamentNameLabel" Text="{Binding TournamentName}"
TextColor="{StaticResource textColor}" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
BackgroundColor="{Binding Selected, Converter={StaticResource colorConvert}}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
ViewModel 代码:
public HistoricalStandingsData _selectedItem;
public HistoricalStandingsData SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
if(_selectedItem != null)
_selectedItem.Selected = false;
_selectedItem = value;
if (_selectedItem != null)
_selectedItem.Selected = true;
TournamentLabelName = _selectedItem.TournamentName;
OnPropertyChanged(nameof(SelectedItem));
//OnPropertyChanged(nameof(_selectedItem.Selected));
}
}
}
我已经为转换器添加了<ContentPage.Resources>
【问题讨论】:
-
Collection 的选择跟踪通常是通过 CollectionView 完成的。请参阅我写的旧 MVVM 介绍中的第 8 点:social.msdn.microsoft.com/Forums/vstudio/en-US/…
-
我假设您的数据源需要实现“INotifyPropertyChanged”,以便在属性更新时通知 burbs。
-
@orhtej2 :感谢您的建议,但这不起作用:(
-
@Hudhud 的事情是,您所做的只是将绑定源更新为整个 ListView,您需要做的是在
HistoricalStandingsData的各个属性上实现INotifyPropertyChanged,因为这就是您的转换器是必然的。 -
你应该使用一个baseViewModel,它为你的所有viewModels实现INotifyPropertyChanged,因为orthej2是正确的。这是使用 baseViewModel 的最简单方法 :)
标签: c# xaml xamarin mvvm xamarin.forms