[英]How to change the background color of `TextCell` inside `ListView` in Xamarin Forms?
[英]Not able to change the Background color of Frame inside CollectionView in Xamarin forms
我想更改Frame 的背景颜色。 我尝试了很多方法,比如设置 Focused 事件、触发器和背景颜色属性的绑定对我来说都不起作用。 这是我的 xaml 代码。
<StackLayout Padding="10">
<CollectionView x:Name="list" ItemsSource="{Binding samplelist}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" HorizontalItemSpacing="10" VerticalItemSpacing="10" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Green" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Frame CornerRadius="10" HasShadow="False" BackgroundColor="{Binding BackgroundTest,Mode=TwoWay}" HeightRequest="75" Margin="5,0,0,0" >
<StackLayout Orientation="Vertical">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Source={x:Reference test}, Path=BindingContext.textselected}"
CommandParameter="{Binding .}"/>
</StackLayout.GestureRecognizers>
这是我的代码 model
private string _backgroundTest;
public string BackgroundTest
{
get { return _backgroundTest; }
// set => SetProperty(ref _backgroundTest, value);
set
{
if (value == _backgroundTest)
return;
_backgroundTest = value;
OnPropertyChanged(nameof(BackgroundTest));
}
}
private async void clicked(Test test)
{
BackgroundTest = "#F95F62";
}
我参考了以下链接How to change color of Frame control when clicked in Xamarin.Forms with MVVM
但没有任何效果。我不知道如何解决这个问题。 有什么建议么?
BackgroundColor 需要一种颜色,但您返回的是一个字符串。 尝试使用转换器,或者只使用颜色属性而不是字符串
选项 A:使用值转换器将字符串转换为颜色(查看文档)
创建转换器 class
将其添加到您的 App.Xaml
修改你的框架绑定 Xaml
<Frame CornerRadius="10" HasShadow="False" BackgroundColor="{Binding BackgroundTest,Mode=TwoWay, Converter={StaticResource colorConverter}}" HeightRequest="75" Margin="5,0,0,0" >
选项 B:将您的绑定修改为 Color 类型
private Color _backgroundTest;
public Color BackgroundTest
{
get { return _backgroundTest; }
set
{
if (value == _backgroundTest)
return;
_backgroundTest = value;
OnPropertyChanged(nameof(BackgroundTest));
}
}
private async void clicked(Test test)
{
BackgroundTest = ColorConverters.FromHex("#F95F62");
}
对于这两种情况:
在您的代码中,Frame 的 BackgroundColor 位于 CollectionView 内,因此绑定将在 Item 内查找属性。 它应该在 ViewModel 中查看
BackgroundColor="{Binding Source={RelativeSource AncestorType={x:Type local:ItemsViewModel}},Path=BackgroundTest}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.