How to customise wp7 toolkit ToggleSwitch - windows-phone-7

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

Related

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.

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>

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

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