Skip to content

Instantly share code, notes, and snippets.

@michael-hawker
Last active May 14, 2024 07:23
Show Gist options
  • Save michael-hawker/6d49e014015a8e122670437bd5c20fc1 to your computer and use it in GitHub Desktop.
Save michael-hawker/6d49e014015a8e122670437bd5c20fc1 to your computer and use it in GitHub Desktop.
Advanced UWP MarkupExtension as IValueConverter + XAML Escape Characters
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
namespace MarkupExtensionTest
{
[MarkupExtensionReturnType(ReturnType = typeof(IValueConverter))]
public class BooleanToTextConverter : MarkupExtension, IValueConverter
{
public string TrueText { get; set; }
public string FalseText { get; set; }
public BooleanToTextConverter()
{
}
protected override object ProvideValue()
{
return this;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is bool b && b)
{
return TrueText;
}
return FalseText;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
<Page
x:Class="MarkupExtensionTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MarkupExtensionTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<ToggleSwitch x:Name="MyToggle">Toggle Me!</ToggleSwitch>
<TextBlock Text="{Binding IsOn, Converter={local:BooleanToTextConverter TrueText='Is it True?', FalseText='Not True!'}, ElementName=MyToggle}"/>
<TextBlock Text="{Binding IsOn, Converter={local:BooleanToTextConverter TrueText=Hello\&#x2C; I\&#x27;m True!, FalseText='Really Not True!'}, ElementName=MyToggle}"/>
<TextBlock>
<TextBlock.Text>
<Binding Path="IsOn" ElementName="MyToggle" Mode="OneWay">
<Binding.Converter>
<local:BooleanToTextConverter TrueText="Hello, I'm True!" FalseText="Nope!"/>
</Binding.Converter>
</Binding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</Page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment