【发布时间】:2017-09-27 16:02:25
【问题描述】:
我有一个 Xamarin.Forms 应用程序(顺便说一下,我是 Xamarin 的新手)。我在页面上有很多元素。我想根据视图模型中的属性值设置按钮的颜色。我有一个自定义的 IValueConverter 类,可以根据整数值将整数值转换为不同的颜色对象。
我不太确定如何让它发挥作用。我正在使用 Brian Lagunas 的 prism nuget 包和模板。这是我的示例代码作为图像。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="PlayAlongJ.Views.MainPage"
xmlns:converters="clr-namespace:PlayAlongJ.Converters;assembly=PlayAlongJ"
Title="Play-along with J">
<ContentPage.Resources>
<ResourceDictionary>
<converters:IntToColorConverter x:Name="intToColor"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Margin="15,30">
<StackLayout HorizontalOptions="End" Orientation="Horizontal">
<Label Text="Chest Total" VerticalTextAlignment="Center"/>
<Button x:Name="ChestTotal" Text="{Binding ChestAmount}"
BackgroundColor="Blue"
TextColor="White" WidthRequest="150"></Button>
</StackLayout>
</StackLayout>
</ContentPage.Content>
我面临的第一个问题是,在我的页面资源字典部分中,我无法为我尝试使用的任何资源获取 x:Key 属性。我只得到一个 x:Name 属性。例如,如果我想用语法设置 Style 资源,我只得到 x:Name,而不是 x:Key。我也在尝试使用我的价值转换器。当我将它用作 时,我再次只得到 x:Name,而不是 x:Key。如果我选择在字典资源中使用 x:Name,我会收到一个编译错误,指出该资源需要一个 x:Key,显然我不能使用它,因为它对我不可用。
这是我的 IValueConverter 实现。有人可以告诉我如何正确设置资源和我的转换器吗?我更喜欢在 XAML 中而不是在代码中设置它们。此外,一旦我可以在没有编译错误的情况下设置资源,示例代码行将按钮的 BackgroundColor 设置为我的视图模型中的绑定整数属性。如果整数是负数,我想使用红色,否则,使用值转换器使用其他颜色。
public class IntToColorConverter : IValueConverter
{
public Object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32(value) >= 0 ? Color.Blue : Color.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
非常感谢任何帮助。谢谢。
【问题讨论】:
标签: c# xaml xamarin.forms