Silverlight 4: Trouble with Value Converters - visual-studio

I'm trying to use a value converter. However, VS is complaining about this XAML:
<Grid x:Name="LayoutRoot" Background="White" Height="Auto" Width="Auto">
<Grid.Resources>
<local:DateFormatter x:Key="FormatConverter" />
</Grid.Resources>
The error:
The type 'local:DateFormatter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.
Am I missing an assembly reference, or is my XAML incorrect? I'm trying to follow an example on MSDN.
Update: I added the following attribute to UserControl:
xmlns:local="clr-namespace:MyNamespace"
I also added a DateFormatter class.
Now Intellisense pops up with "local" and "DateFormatter". However, it still gives the same error as above. The error does not occur for other types, such as App.
DateFormatter:
using System;
...
namespace MyNamespace
{
public class DateFormatter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime date = (DateTime) value;
return date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}

Yes - you need to add an xmlns:local="clr-namespace:SilverlightApplication6" to map the namespace and assembly to the XAML namespace local. If you add the converter via Expression Blend, it will put the correct namespace declaration in for you.

As Michael S. Scherotter says, you'll need to add a namespace reference in XAML.
If you're following the MSDN article you'll need to include the following:
xmlns:local="clr-namespace:YOUR-NAMESPACE-HERE"
This is similar to a using statement in C#. It tells XAML where to find your DateFormatter type.
Update:
I'm not sure what's going wrong for you.
The following works for me (applying your DateFormatter code but in a different namespace):
MainPage.xaml
<UserControl x:Class="SilverlightApplication2.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:local="clr-namespace:SilverlightApplication2">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<local:DateFormatter x:Key="FormatConverter" />
</Grid.Resources>
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Text="{Binding FooDate, Converter={StaticResource FormatConverter}}"/>
</Grid>
</UserControl>
MainPage.xaml.cs
using System;
using System.Windows.Controls;
namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
var foo = new Foo { FooDate = DateTime.Now };
DataContext = foo;
}
}
public class Foo
{
public DateTime FooDate { get; set; }
}
}
DateFormmatter.cs
using System;
using System.Windows.Data;
namespace SilverlightApplication2
{
public class DateFormatter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

Related

How to pass value from xamarin page to ivalueconverter class properties Xamarin Forms

I have a class of IValueConverter with a property named myValue which I want to divide the ivalueconverter by its property myValue! But, I want to know if it is possible to pass the myValue from xamarin page to ivalueconverter? If yes, how?
IvalueConverter
class salesUIbtnWidth : IValueConverter
{
public double myValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value / myValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Try Implementing the class
<Button Text="Click me" HorizontalOptions="Center" VerticalOptions="Center"
CornerRadius="15" WidthRequest="{Binding Source={x:Reference
frame}, Path=Width,Converter={StaticResource salesUIbtnWidth}}">
</Button>//how to bind also the MyValue
All I want is to know how to set myValue in page and pass it to (IvalueConverter) from xamarin during runtime!!
You can pass the value by ConverterParameter.
You can refer to the sample code:
<Label Text="{Binding Red,
Converter={StaticResource doubleToInt},
ConverterParameter=255,
StringFormat='Red = {0:X2}'}" />
<local:DoubleToIntConverter x:Key="doubleToInt" />
DoubleToIntConverter.cs
public class DoubleToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)Math.Round((double)value * GetParameter(parameter));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value / GetParameter(parameter);
}
double GetParameter(object parameter)
{
if (parameter is double)
return (double)parameter;
else if (parameter is int)
return (int)parameter;
else if (parameter is string)
return double.Parse((string)parameter);
return 1;
}
}
For more, you can check: Binding Converter Parameters
According to your question this is what you need to do!
Following #Jessie Zhang example
<Button HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"
HeightRequest="{Binding Source={x:Reference frame}, Path=Height,
Converter={StaticResource doubleToInt}, ConverterParameter=enterYOURvaluHERE}"></Button>
If you don't want to use parameter, you can define MyValue when you create the converter.
<ContentPage.Resources>
<app1:MyConverter x:Key="myConverter" MyValue="255"/>
</ContentPage.Resources>

Xamarin changing binding context value during runtime

Please question might be funny, not be funny at all or confusing! But the simple goal I wanted is to changing the value of binding context in xamarin.forms on runtime!!
IvalueConverter
class LoginFrameHeight : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value / 1.9;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Resource Dictionary
<ResourceDictionary>
<local:LoginFrameHeight x:Key="frameHeight"/>
</ResourceDictionary>
Setting Frame Height
<Frame CornerRadius="15"
HeightRequest="{Binding Source={x:Reference frame},
Path=Height,Converter={StaticResource frameHeight}}" Padding="0"></Frame>
Code works fine! My problem is that I have about three (3) frames to apply different HeightRequested using same process! is it possible to change the (1.9) in IvalueConverter during
runtime, so that I can use the same class LoginFrameHeight instead of creating different classes for the frames?
The answer is "YES" you can use ConverterParameter here is quick ref: This official documentation will show more
Example:<Label Text="{Binding Red,Converter={StaticResource doubleToInt}, ConverterParameter=255, StringFormat='Red = {0:X2}'}" />

Xamarin.Forms setting Image Source in shared project

I have a Xamarin.Forms solution with Android and iOS projects.
I want the same images to be in both applications.
I know I can add the same image to both projects code seperately, but that doesn't sound very elegant.
I want to have only one image referred to by both projects, from the code in the shared project.
My images are in the shared project, and are Embedded Resource
SharedProject
|
- Resources
|
- icon192.png
My XAML (shared project)
<ContentPage xmlns:myExtensions="clr-namespace:LibraryApp.Extensions;assembly=App">
<Image x:Name="image2"
VerticalOptions="Center" HeightRequest="50" Aspect="AspectFit" />
<Image Source="{myExtensions:ImageResourceExtension Resources.icon192.png}"
VerticalOptions="Center" HeightRequest="50" Aspect="AspectFit" />
</ContentPage>
My code-behind (shared project)
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
image2.Source = ImageSource.FromResource("LibraryApp.AndroidClient.Resources.icon192.png");
}
}
The first Image, image2 works perfectly when set from code-behind.
But I don't want to have to deal with images in code-behind, because they are a presentation detail, not implementation.
So my extension method to try and solve this
namespace LibraryApp.Extensions
{
[Preserve(AllMembers = true)]
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null) return null;
// do some work to get the name of the correct assembly/project, here
// var stream = Assembly.GetCallingAssembly().GetManifestResourceStream(Source);
// just for testing, return something we know that works
return ImageSource.FromResource("LibraryApp.AndroidClient.Resources.icon192.png");
}
}
}
This extension method does get called from the other image (with the correct Source parameter).
Even though the code is effectively exactly the same, I cannot get an image using the extension method.
I get a FileImageSourceHandler: Could not find image or image file was invalid.
How would you solve this problem?
Typical, after spending literally a day on this, I figure it out 20m after asking the question...
One solution is to add an IValueConverter
public class ResourceConverter : IValueConverter
{
public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
if (value is not String filename) throw new ArgumentNullException(nameof(value));
var nameOfAssembly = Assembly.GetExecutingAssembly().GetName().Name;
return ImageSource.FromResource($"{nameOfAssembly}.{filename}");
}
public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
And then in the XAML
<ContentPage xmlns:converter="clr-namespace:GPS4Flight.Converter">
<ContentPage.Resources>
<converter:ResourceConverter x:Key="ResourceConverter" />
</ContentPage.Resources>
<Image Source="{Binding Source=Resources.icon192.png, Converter={StaticResource ResourceConverter}}"
VerticalOptions="Center" HeightRequest="50" Aspect="AspectFit" />
</ContentPage>
Notice I needed {Binding Source=[nameOfFile] for it to work.

How to set DatePicker value equal yesterday in xaml in xamarin.form?

To set the Date attribute in xaml equal today we can use Today attribute as following:
xmlns:system="clr-namespace:System;assembly=mscorlib"
<DatePicker Date="{x:Static system:DateTime.Today}"/>
I've tried to set it by using AddDays method but it couldn't help.
<DatePicker Date="{x:Static system:DateTime.Today.AddDays(-1)}"/> Does not work.
So is there a way?
After some discussions the best answer I have found is using a helper like following:
In xaml:
xmlns:helpers="clr-namespace:Helpers"
<DatePicker Date="{x:Static helpers:DateTimeHelper.Yesterday}"/>
While helper is:
namespace Helpers
{
public class DateTimeHelper {
public static System.DateTime Yesterday
{
get { return System.DateTime.Today.AddDays(-1); }
}
}
}
You can set the date from the controller.
<DatePicker x:Name="PostingDatePicker" />
PostingDatePicker.Date = DateTime.Today.AddDays(-1);
Another way is that you bind the date from your ViewModel,
Xaml
<DatePicker x:Name="PostingDatePicker" Date="{Binding PostingDate}"/>
ViewModel
public DateTime PostingDate {get; set;}
PostingDate = DateTime.Today.AddDays(-1);
Updated Answer:
If you want to update the date only through XAML, you can use converters,
<DatePicker x:Name="PostingDatePicker" Date="{Binding PostingDate, Converter={local:DateConverter}}"/>
create a class which inherits IValueConverter,
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
return DateTime.Today.AddDays(-1);
}
catch (Exception)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
At runtime, your datepicker date will be updated with yesterday's date.

Value Converter not working in Xamarin

A bit confused here, I seem to have followed the steps that would allow me to make use of value converters.
I have my converter defined with a key, as such:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Title="Article"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:XamarinMobile.Controls;assembly=XamarinMobile"
xmlns:converters="clr-namespace:XamarinMobile.Converters;assembly=XamarinMobile"
x:Class="XamarinMobile.ArticlePage">
<ContentPage.Resources>
<ResourceDictionary>
<converters:FontSizeConverter x:Key="FontSizeMapper"></converters:FontSizeConverter>
</ResourceDictionary>
</ContentPage.Resources>
I then make use of my converter in my XAML, as such:
<ContentView Padding="10,-10,10,0" Grid.Row="2" Grid.Column="0">
<StackLayout>
<Label x:Name="LabelAuthor" FontSize="{Binding 20, Converter={StaticResource FontSizeMapper}, ConverterParameter=20}" />
<Label x:Name="LabelPublishDate" FontSize="{Binding 10, Converter={StaticResource FontSizeMapper}, ConverterParameter=10}"/>
</StackLayout>
</ContentView>
And here is my actual converter code:
namespace XamarinMobile.Converters
{
public class FontSizeConverter : Xamarin.Forms.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(value is double)
{
return App.NormalizeFontSize((double)value);
} else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
I then put a break point in my value converter, but it never hits. Is there something obvious that I'm missing here? I'm pretty sure I followed the directions to a tee.
Your breakpoint isn't being hit due to what Gerald Versluis said. Your binding is broken. What your binding is saying is: Bind to the property named "10" on the BindingContext, and use the Converter FontSizeMapper, passing it an extra ConverterParameter of 10. "10" isn't a valid property name, so the binding is breaking. If you look in your logs, you should see a message similar to: "Binding: '10' property not found on ..."
One way to fix it would be to remove the "Path" you're trying to bind to and only make use of the ConverterParameter (assuming you don't need to bind to any real properties):
FontSize="{Binding Converter={StaticResource FontSizeMapper}, ConverterParameter=20}"
Note that you'll need to make use of the parameter in the converter, rather than the value (eg. if (parameter is double)).
If you don't need to bind to any properties, another way to fix it would be to use a custom markup extension instead.
[ContentProperty("FontSize")]
public class FontSizeMapperExtension : IMarkupExtension
{
public double FontSize { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return App.NormalizeFontSize(FontSize);
}
}
Then you could use it in your XAML like:
FontSize="{converters:FontSizeMapper FontSize=10}
Edit
An example of binding to a property on an object:
public class YourViewModel
{
public double VMFontSize { get; set; }
}
public partial class ArticlePage : ContentPage
{
public ArticlePage()
{
InitializeComponent();
// NOTE: You'd probably get your view-model another way
var viewModel = new YourViewModel { VMFontSize = 10 };
BindingContext = viewModel;
}
}
Now that your view-model is set as the binding context, you can set the binding like:
FontSize="{Binding VMFontSize, Converter={StaticResource FontSizeMapper}}"
What this says is: Bind the FontSize property on the label to the VMFontSize property on the current BindingContext (your view-model), using the converter to map between the view-model's VMFontSize and the Label's FontSize. I left the ConverterParameter off here as it isn't really needed in this example, but you could pass one if you need it.
I would do this a different way, using a custom attached property, see more on attached properties here https://developer.xamarin.com/guides/xamarin-forms/xaml/attached-properties/
Here is a sample for your scenario, first we need to define an attached property, it can be in any class, I called mine FontHelper
namespace App23
{
public static class FontHelper
{
public static readonly BindableProperty FontSizeProperty =
BindableProperty.CreateAttached("FontSize", typeof(double), typeof(FontHelper), 0d, propertyChanging:OnPropertyChanging);
public static bool GetFontSize(BindableObject view)
{
return (bool)view.GetValue(FontSizeProperty);
}
public static void SetFontSize(BindableObject view, bool value)
{
view.SetValue(FontSizeProperty, value);
}
private static void OnPropertyChanging(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is Label)
{
var label = bindable as Label;
double fontSize = (double)newValue;
// normalize your font size here
label.FontSize = fontSize;
}
}
}
}
Then to use it in XAML, it looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App23"
x:Class="App23.MainPage">
<Label Text="Welcome to Xamarin Forms!"
VerticalOptions="Center"
HorizontalOptions="Center" local:FontHelper.FontSize="50"/>
</ContentPage>

Resources