Hello,
If Converter is the way to go, then how would I accomplish that?
Yes, you can do this by Converter.
Firstly, you create a class that extend IValueConverter
like following code.
As note: if you use var GetColor= Application.Current.Resources[colorKey];
to get value from Resources, you will get null, this is a known issue: Can't find global resource dictionary #8799, I set the color directly with Color.FromRgb(value ,value, value);
and change the type of colorKey
.
public class DeviceToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Device device= value as Device;
Color colorKey;
switch (device.Status)
{
case "Connected and OK state":
//"DeviceConnectedAndOkState"
colorKey = Color.FromRgb(255,0, 0);
break;
case "Not connected state":
// colorKey = "DeviceNotConnectedState";
colorKey = Color.FromRgb(0, 255, 0);
break;
case "Alarm state":
// colorKey = "DeviceAlarmState";
colorKey = Color.FromRgb(0, 0, 255);
break;
case "Error state":
// colorKey = "DeviceErrorState";
colorKey = Color.FromRgb(0, 255, 255);
break;
default:
return new Color(0, 0, 0);
}
// var GetColor= Application.Current.Resources[colorKey]; You will get the null value, this is a known issue: https://github.com/dotnet/maui/issues/8799
return colorKey;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return new Color(0, 0, 0);
}
}
Then you can use this converter in the ContentPage.Resources
with following code. I add two buttons for testing and bind two properties with Converter.
<ContentPage.Resources>
<ResourceDictionary>
<local:DeviceToColorConverter x:Key="deviceToColor" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Orientation="Vertical" >
<Button Text="Click Me!" TextColor="{Binding MyDevice, Converter={StaticResource deviceToColor}}"/>
<Button Text="Click Me!" TextColor="{Binding MyDevice2, Converter={StaticResource deviceToColor}}"/>
</StackLayout>
Here is my testing viewmodel.
public class DevicesViewModel
{
public Device MyDevice { get; set; } =new Device() {Status= "Connected and OK state" };
public Device MyDevice2 { get; set; } = new Device() { Status = "Not connected state" };
public DevicesViewModel()
{
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.