Xamarin changing binding context value during runtime - xamarin

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}'}" />

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>

Unified place for resources used in XAML and cs files?

It happens that I define a ResourceDictionary for the app colors to use it in XAML files, and have a static class for these colors to use in the cs code:
for example:
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Themes.AppTheme">
<Color x:Key="BrandColor">#ffd92e</Color>
<Color x:Key="BgColor">#343433</Color>
</ResourceDictionary>
And the opposite class:
public static class AppColors
{
public static readonly Color BrandColor = (Color)Application.Current.Resources["BrandColor"];
public static readonly Color BGColor = (Color)Application.Current.Resources["BgColor"];
}
Another scenario,I use icons font in both xaml and cs,
in XAML it looks like , and in cs it's: \ue8d5 . I want to save them in a file where I can reference them by a meaningful names in XAML and cs like:
IconBell = \ue8d5
Is it possible to define resources like those in one place and use them in both XAML and code?
About the colors issue, it's very easy to solve it. You basically have to create a class containing your colors, and reference it in your XAML, with the x:Static extension.
You can do the same for solving your icons issue, but you'll probably need to create a converter for using it in XAML. For example, the important part of your icon value is the "e8d5" part, but in C# you use the "\u" and in the XAML you use the "&#x". You'll have to create a class with the icons, reference it in the XAML using the x:Static extension and use a converter to convert from C# to XAML, for example:
public class IconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
string icon = System.Convert.ToString(value);
return icon.Replace("\u", "&#x");
}
catch (Exception)
{
throw new InvalidCastException("The value is not a valid string.");
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
With this, you can unify your styles in a unique C# class, and just reference it in your XAML.

Itemdatabound event of longlistselector control in Windows phone 7

I want to control the visibility of an image (inside a dynamically bind longlistselector control), depending on a binding value (say if somevalue>0 then make that image visible otherwise invisible).But there is no such event like itemdatabound in the longlistselector to accomplish this task, I am new to windows phone development, and really don't have an idea how to do this.Please help me guys.
Thanks,
Use a ValueConverter
public class BoolToVisiblityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value
? Visibility.Collapsed
: Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
A common way to achieve this would be to bind the visibility property of the Image to a property on your bound data object. Often, the property on the data would be a boolean and a converter would be used to convert the boolean to a Visibility enum value. E.g.,
<Image Visibility = {Binding IsVisible, Converter={StaticResource myBoolToVisibilityConverter} />
See binding with converters example

How to customise wp7 toolkit ToggleSwitch

I have the WP7 toolkit and am using the toggle switch.
At the moment it displays On or Off.
I know you can customise it using the the content template and the sample code supplied with the tookit shows just that, but it I can't find a way of changine On/Off to something else.
I want to display Yes and No.
I created my own value converter that was bound to the same boolean property on my view model as IsChecked. So on the view it looked like:
<toolkit:ToggleSwtich IsChecked="{Binding Completed}" Content="{Binding Completed, Converter={StaticResource YesNoConverter}" />
Hum since the "On" et "Off" strings come from a converter set in a private method in the source code, I don't see a lot of alternative : http://silverlight.codeplex.com/SourceControl/changeset/view/55144#1325068
Change the source code to have something more flexible ?
There is a much easier way, set the content to No and then create a event handler for each toggle to make it say Yes and then No:
private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
{
togButton.Content = "Yes";
}
private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
{
togButton.Content = "No";
}
I know that the question is quite old, but I think that this answer may be useful because there's no need to recompile the control's code.
We can bind the Content to the IsChecked property and use a Converter that returns our custom string.
This is what I did for my project:
<toolkit:ToggleSwitch SwitchForeground="{StaticResource PhoneAccentBrush}"
Grid.Row="3" Grid.Column="1"
Header="{Binding Path=LocalizedResources.MyLabel, Source={StaticResource LocalizedStrings}}"
Content="{Binding IsChecked, Converter={StaticResource SwitchOnOffConverter}, RelativeSource={RelativeSource Self}}"/>
where the SwitchOnOffConverter is this one:
public class SwitchOnOffConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool) value) ? AppResources.YesText : AppResources.NoText;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}

Silverlight 4: Trouble with Value Converters

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();
}
}
}

Resources