我以前看过一些答案,但没有什么能真正帮助我。
我还有一门课DecideModel
(这将是从数据库中检索到的数据集,但出于这个问题的目的,我添加了一个 ObservableCollection),其中包含
static DecideModel()
{
All = new ObservableCollection<DecideModel>
{
new DecideModel
{
DatePerformed = new DateTime(2015, 4, 06),
Result = "Maybe"
},
new DecideModel
{
DatePerformed = new DateTime(2015, 4, 05),
Result = "No"
},
new DecideModel
{
DatePerformed = new DateTime(2015, 4, 04),
Result = "Yes"
}
};
}
public DateTime DatePerformed { set; get; }
public string Result { set; get; }
public static IList<DecideModel> All { set; get; }
}
在我的 XAML 代码中,我有
<ContentPage.Resources>
<ResourceDictionary>
<Color x:Key="Maybe">#ffddbc21</Color>
<Color x:Key="Yes">#3CB371</Color>
<Color x:Key="No">#B22222</Color>
<Color x:Key="Depends">#ffd78800</Color>
</ResourceDictionary>
</ContentPage.Resources>
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{StaticResource {BindingSource Result}}" />
我正在尝试根据我从对象获得的结果动态设置标签的背景颜色。
如果您对如何操作有任何想法,请告诉我。我正在寻找任何有用的选项。
最佳答案
对于无需太多开销即可实现此目的的纯 XAML 方法,您可以使用 DataTrigger
.请注意,您可以根据需要为每个触发器添加任意数量的 setter ,这比之前建议的解决方案稍微灵活一些,它还将 View 逻辑保留在 View 中应有的位置。
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Yes">
<Setter Property="BackgroundColor" Value="#3CB371" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding Result}" Value="No">
<Setter Property="BackgroundColor" Value="#B22222" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Maybe">
<Setter Property="BackgroundColor" Value="#ddbc21" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Depends">
<Setter Property="BackgroundColor" Value="#d78800" />
</DataTrigger>
</Label.Triggers>
</Label>
请注意,您可以通过设置
BackgroundColor
来删除其中一个触发器。属性设置为合理的默认值(在这种情况下可能是“取决于”)。
关于xaml - 根据数据绑定(bind)值设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095689/