【发布时间】:2020-06-04 20:07:18
【问题描述】:
我创建了一个自定义控件,我想在单击后更改颜色。我可以成功加载它,但是一旦我运行我的函数并想要更改颜色,什么也没有发生。当我尝试使用常规元素(按钮、标签)时,它可以工作。
自定义控件(即内部带有简单标签的 Grid):
public partial class CustomGrid : Grid
{
public static readonly BindableProperty ItemProperty = BindableProperty.Create(nameof(Item), typeof(Item), typeof(CustomGrid), propertyChanged: ItemChanged);
public static readonly BindableProperty CustomColorProperty = BindableProperty.Create(nameof(IsAnonymousSubColor), typeof(Color), typeof(CustomGrid), propertyChanged: CustomColorChanged);
public Color CustomColor
{
get { return (Color)GetValue(CustomColorProperty); }
set { SetValue(CustomColorProperty, value); }
}
static void CustomColorChanged (object bindable, object oldValue, object newValue)
{
var x = bindable as CustomGrid;
if (x.Item != null)
{
x.myLabelInMyXaml.BackgroundColor = x.CustomColor;
}
}
static void ItemChanged (object bindable, object oldValue, object newValue)
{
var x = bindable as CustomGrid;
}
public Item Item
{
get { return (Item) GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
public CustomGrid()
{
InitializeComponent();
}
}
这是我的 xaml,在这里我将它绑定到 viewmodel 颜色代码(绑定在其他元素上效果很好,即使我在同一个 stacklayout 中尝试它)。
<StackLayout BackgroundColor="Transparent"
Padding="0,10,0,0"
VerticalOptions = "StartAndExpand"
BindableLayout.ItemsSource="{Binding newsService.FeedList}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout>
<controls:CustomGrid Item ="{Binding .}"
CustomColor = "{Binding BindingContext.CustomColorViewModel, Source={x:Reference ParentView}}" />
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
视图模型:
private Color _CustomColorViewModel;
public Color CustomColorViewModel
{
get { return _CustomColorViewModel; }
set
{
_CustomColorViewModel = value;
RaisePropertyChanged("CustomColorViewModel");
}
}
我在加载后更改它:
public void ChangeColor ()
{
CustomColorViewModel = Color.Red;
}
自定义控件的XAML:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:Neutral.Controls"
xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
xmlns:fftransformations="clr-namespace:FFImageLoading.Transformations;assembly=FFImageLoading.Transformations"
xmlns:yummy="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView"
x:Name="ParentView"
x:Class="Project.Controls.CustomGrid">
<Label x:Name = "myLabelInMyXaml" BackgroundColor = "{Binding CustomColorViewModel}"/>
</Grid>
但是自定义控件背景颜色没有变化。它在我最初加载时有效,但在我尝试更新时无效。请注意,我对其他元素没有问题,只有这个自定义控件。
不知道为什么它不更新颜色。
【问题讨论】:
-
你能发布
CustomGrid的 XAML,很可能你必须在CustomColorChanged中执行 x.BackgroundColor=newColor 而你不需要 x:Reference Parentview -
也更新了 xaml 代码。
标签: c# xamarin xamarin.forms xamarin.android xamarin.ios