Adding additional string to {x:Bind} in XAML Universal Windows Platform - xaml

I am new to XAML. I would like to add additional string to x:bind
I have tried
<AppBarToggleButton Icon="Phone" Label="E-Mail To {x:Bind e_mail}" />
<AppBarToggleButton Icon="Phone" Label="{"E-Mail To" + x:Bind e_mail}" />
I would like to get "E-Mail to email#email.com"
But no success. Thanks for help.

Create a converter for this:
public sealed class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format(parameter.ToString(), value);
}
public object ConvertBack(object value, Type targetType, object parameter,
string language)
{
throw new NotImplementedException();
}
}
Add this to yor page/control/app resources:
<converters:StringFormatConverter x:Key="StringFormatConverter" />
And then use it like this:
<TextBlock Text="{x:Bind e_mail}"
Converter="{StaticResource StringFormatConverter}"
ConverterParameter="E-Mail To {0}!" />

Instead of creating your own StringFormatConverter you can use the builtin converter from Microsoft:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:Microsoft.Toolkit.Uwp.UI.Converters"
mc:Ignorable="d">
<converter:StringFormatConverter x:Key="StringFormatConverter"/>
</ResourceDictionary>
There are also some other useful builtin converters, check them out:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.toolkit.uwp.ui.converters?view=win-comm-toolkit-dotnet-7.0

Related

How to translate Xamarin Xaml IValueConverter into C#?

Can you please help me translate this Xamarin xaml into c#?
BackgroundColor="{Binding IconColor, Converter={StaticResource LocalHexColorFromStringConverter}}"/>
Thanks!
You can translate it by MyBtn.SetBinding(Button.BackgroundColorProperty, "IconColor", BindingMode.OneTime, new LocalHexColorFromStringConverter()) ;
I make a test with Button's background color.
Button MyBtn = new Button();
MyBtn.Text = "test";
MyBtn.SetBinding(Button.BackgroundColorProperty, "IconColor", BindingMode.OneTime, new LocalHexColorFromStringConverter()) ;
Content = MyBtn;
Here is LocalHexColorFromStringConverter.cs
public class LocalHexColorFromStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Color.FromHex((string)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
Can I ask what the difference is between "new LocalHexColorFromStringConverter()" and "converter: LocalHexColorFromStringConverter()" ?
Do you mean "new LocalHexColorFromStringConverter()" and "converter: LocalHexColorFromStringConverter"?
If so, they are same, converter: LocalHexColorFromStringConverter is wirte type in Xaml , converter: is prefix, it explains the specific path of this class, If you want to call it from any pages, you need to write it in the App.xaml.
For example, you add add it in the App.xaml.
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:OAuthGoogleDemo"
x:Class="OAuthGoogleDemo.App">
<Application.Resources>
<ResourceDictionary>
<converters:LocalHexColorFromStringConverter x:Key="HexColorFromStringConverter" />
</ResourceDictionary>
</Application.Resources>
</Application>
Then use it in the Mainpage.xaml with Converter={StaticResource HexColorFromStringConverter}}"

Type not found on XAML namespace

I am trying to access to method class from XAML file.
My class is on folder: project.Utils.
Adding on xaml Content Page:
xmlns:local="project.Utils"
I try to use myConverterMethod class inside Utils folder and use it as:
Converter={StaticResource myConverterMethod}
but error Type myConverterMethod not found in xmlns project.Utils.
Where is my fault?
You can use
xmlns:local="clr-namespace:project.Utils;assembly=project"
It is not possible to refer to a Method within a specific class but to a IValueConverter.
In order to achieve what you want, you need to define a class that implements IValueConverter:
public class IntToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value != 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? 1 : 0;
}
}
Define the created converter in accessible scope: Page/View or Application. By scope I mean resources:
<ContentPage.Resources>
<ResourceDictionary>
<local:IntToBoolConverter x:Key="intToBool" />
</ResourceDictionary>
</ContentPage.Resources>
and finally consume the converter in the next way:
<Button Text="Search"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
IsEnabled="{Binding Source={x:Reference entry1},
Path=Text.Length,
Converter={StaticResource intToBool}}" />
Xamarin has a very nice documentation that will answer all your questions and it usually has a good code samples.

Xamarin Style staticresource binding

would it be possible to databind a static resource in Xamarin Forms?
Something like
Style="{StaticResource {Binding foo, StringFormat='SomeStyle{0}'}}"
Thanks
What you probably want is a Value Converter that handles locating the StaticResource for you. Full Microsoft Documentation here.
On your XAML element, you'd do something like this:
<Entry Style="{Binding foo, Converter={StaticResource FooToStyleConverter}}"/>
Your converter would work something like this:
public class FooToStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var someValue = (string)value; // Convert 'object' to whatever type you are expecting
// evaluate the converted value
if (someValue != null && someValue == "bar")
return (Style)App.Current.Resources["StyleOne"]; // return the desired style
return (Style)App.Current.Resources["StyleTwo"];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Usually unused, but inverse the above logic if needed
throw new NotImplementedException();
}
}
Lastly, set up your converter as a Static Resource in App.xaml (or as a local resource on the page) so your page can properly reference it
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBindingDemos">
<ContentPage.Resources>
<ResourceDictionary>
<local:FooToStyleConverter x:Key="FooToStyleConverter" />
....

System.Type as property of converter - only works with unused property in code behind

I have a IValueConverter that has a System.Type property which is set in XAML.
Converter:
internal class EnumTypeConverter : IValueConverter
{
public Type TypeToDisplay { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
return TypeToDisplay?.FullName;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
XAML:
<Page
x:Class="UWPSystemTypeConverterTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:UWPSystemTypeConverterTest.Converter"
xmlns:enums="using:UWPSystemTypeConverterTest.Enum"
mc:Ignorable="d">
<Page.Resources>
<converter:EnumTypeConverter x:Key="Converter" TypeToDisplay="enums:CustomEnum" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="{Binding Converter={StaticResource Converter}}" />
</Grid>
</Page>
When I run the application, I get following error:
Windows.UI.Xaml.Markup.XamlParseException: 'The text associated with
this error code could not be found.
Failed to create a
'UWPSystemTypeConverterTest.Converter.EnumTypeConverter' from the text
'enums:CustomEnum'. [Line: 14 Position: 56]'
If I add a property of type CustomEnum to the code- behind file, which is never used, the application works.
the changed code- behind- File:
public sealed partial class MainPage : Page
{
public CustomEnum WithThisPropertyTheAppWorks { get; set; }
public MainPage()
{
InitializeComponent();
this.DataContext = this;
}
}
The complete project for reproduction is here: https://github.com/SabotageAndi/UWPSystemTypeConverterTest
Line to uncomment is https://github.com/SabotageAndi/UWPSystemTypeConverterTest/blob/master/UWPSystemTypeConverterTest/MainPage.xaml.cs#L13
I suspect that an optimiser of UWP is causing this problem.
Is this really the case?
How can I fix the error without the unused property in the code-behind file?
Targeting UWP Build 10240, a viable work around is to add a dummy instance of the targeted enum in static resources of the page before instantiating the converter.
<Page.Resources>
<enums:CustomEnum x:Key="WorkAround">CustomEnumValue</enums:CustomEnum>
<converter:EnumTypeConverter x:Key="Converter" TypeToDisplay="enums:CustomEnum" />
</Page.Resources>
Info from a MSFT employee on a MVP mailing list:
This behaviour is a current limitation of UWP.
The XAML compiler and the runtime don't support System.Type- typed properties. So the needed metadata is not generated and the runtime can not convert the string to the type.
But because of the public properties on the code-behind, the compiler generates the needed metadata now. I am not that happy with the work around, but it is better than other solutions (e.g. a string property with the fullname to the type).

CheckBox binding to element issue in WP8.1

I have a simple XAML:
<CheckBox x:Name="chkShowGrid" IsThreeState="False" IsChecked="False">Show content</CheckBox>
<Grid Visibility="{Binding IsChecked, ElementName=chkShowGrid}">
<TextBlock>Some content goes here</TextBlock>
</Grid>
This XAML works well in WinRT Windows 8.1 application. When I trying it in WP8.1 application it works in designer (shows or hides grid depend of checkbox value), but not on the phone. Why?
UPDATE:
I have universal 8.1 app and if use converter then shows me exception:
error CS0012: The type 'Type' is defined in an assembly that is not
referenced. You must add a reference to assembly 'System.Runtime,
Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Converter code:
class BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return false;
return (bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
In XAML
<Page.Resources>
<local:BoolConverter x:Name="ThatsMyConverter"/>
</Page.Resources>
........
<Grid Visibility="{Binding IsChecked, ElementName=chkShowSettings,Converter={StaticResource ThatsMyConverter}}">
Your converter returns a boolean value and you are trying to assign a bool to Visibility which can only take Visible or Collapsed as possible values. Try returning Visibility from your converter instead of bool. That should work. For example in your converter:
if (value == null) return Visibility.Collapses;
var val = (value as bool);
if (val)
return Visibility.Visible;
else
return Visibility.Collapsed;