Display label text in uppercase using xaml in Xamarin.Forms - c#

I have an username label and need to view this as uppercase but this should only relate to the UI. The data (string) should be saved in the db as actual case whatever it is. Could anyone tell me if there is anyway to convert it to uppercase without doing so through the code behind?

You can use Label.TextTransform with TextTransform.Uppercase.
XAML
<Label TextTransform="Uppercase" />
C#
var label = new Label
{
TextTransform = TextTransform.Uppercase
};

As you're aware you can do this from the code behind as such:
string data = "my data";
UILabel myLabel = new UILabel();
myLabel.Text = data.ToUpper();
So bearing in mind that you don't want to do it this way you would need to derive from UILabel and create your own, then simply add the ToUpper() onto the end of the get;set; values of the Text property.
using CoreGraphics;
using System;
using UIKit;
namespace MyApp.Controls
{
partial class Control_UpperLabel : UILabel
{
public Control_UpperLabel IntPtr handle) : base(handle)
{
//
}
public Control_UpperLabel()
{
//
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
}
public override string Text { get => base.Text.ToUpper(); set => base.Text = value.ToUpper(); }
}
}
EDIT: As per comments below, here is an alternative solution for Xamarin.Forms
This uses a value converter as part of a binding solution. It's also been slightly amended to use the suggestion by clint in the comments below. Thanks.
public class StringCaseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((parameter as string).ToUpper()[0])
{
case 'U':
return ((string)value).ToUpper();
case 'L':
return ((string)value).ToLower();
default:
return ((string)value);
};
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
It would be used in the XAML as such:
Text="{Binding Text, Converter={StaticResource caseConverter}, ConverterParameter=u}}"

Or you can use Bindable property then format the text on the getter :
e.g.:
public static readonly BindableProperty ItemLabelProperty =
BindableProperty.Create(nameof(ItemLabel), typeof(string),
typeof(DetailsLineItemControl), default(string), BindingMode.OneWay);
public string ItemLabel
{
get
{
var value = (string)GetValue(ItemLabelProperty);
return !string.IsNullOrEmpty(value) ? value.ToUpper() : value;
}
set
{
SetValue(ItemLabelProperty, value);
}
}

Related

FontAwesome / Xamarin - Setting Glyph not working from code behind

I missing something here when using FontAwesome on Xamarin... the buttons work fine when setting from xaml file but when I try to set from code behind it doesn't show the icon, here is the scenario:
button working fine:
<Button Grid.Row="0" Grid.Column="4" x:Name="btnIdDav" Padding="10" Margin="3" TextColor="#FFF" BackgroundColor="#565C5A" Clicked="btnIdDav_Clicked" WidthRequest="45">
<Button.ImageSource>
<FontImageSource FontFamily="{StaticResource FontAwesomeSolidOTF}" Glyph="" Color="#fff"/>
</Button.ImageSource>
</Button>
Last time I had to set Glyph from code, I had to do a bad 'workaround' with converter in order to show it, and it worked (icon is showing) in the end:
public const string _dollarGlyph = "\uf155";
public const string _percGlyph = "\uf541";
public class DescGlyphConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Glyph="{Binding DescImage, Converter={StaticResource Key=desconto}}
NOW I want to create a custom button and set the Glyph but the icon is not appearing (tested with both OTF and TTF files):
public static FontImageSource GetImgSource()
{
FontImageSource source = new FontImageSource();
source.FontFamily = Application.Current.Resources["FontAwesomeSolidTTF"].ToString();
source.Glyph = "\uf3e5";
source.Color = Color.FromHex("#fff");
return source;
}
public static Style BtnBack() {
return new Style(typeof(Button))
{
Setters = {
new Setter { Property = Button.ContentLayoutProperty, Value = new ButtonContentLayout(ButtonContentLayout.ImagePosition.Top, 5) },
new Setter { Property = Button.TextProperty, Value = "Back" },
new Setter { Property = Button.ImageSourceProperty, Value = GetImgSource()},
}
};
}
Any sugestions?
Thanks!
Here is the sample code, please change accordingly. I am using the FontFile name directly:
FontImageSource fontImageSource = new FontImageSource()
{
Glyph = "\uf15c",
Color = Color.Black,
Size = 18,
FontFamily = Device.RuntimePlatform == Device.Android ? "FontAwesome.otf#Regular" : null
};
this.IconImageSource = fontImageSource;

Item to Display for Picker don't show up on load

This is Xamarin Forms app. I'm using Fresh MVVM. I have Modification Page, where i can change boolean value with picker (true, false, null).
I have list of boolean values (for each picker - one value and in ViewModel list filled from DB).Bool converts (using converter) to object with two values: Text(string) and Value(bool?) which is class - CheckListValue written below.
The logic - i'm putting some values with picker, saving it to DB and after i can modify it, so on load, i should see chosen value. But picker field - empty.
Here is result, what i see. I should see Binded Item in ItemDisplayBinding, and its Text (Negative, Positive or Empty).
I thought that the problem in Binding, but it seems okay.
<Picker Grid.Row="1" Grid.Column="0" ItemsSource="{Binding CheckListValueList, Mode=TwoWay}"
ItemDisplayBinding="{Binding Text}" SelectedItem="{Binding CheckListProperties.SomeBooleanValue, Mode=TwoWay, Converter={StaticResource BoolToCheckListConverter}}"/>
here is CheckListValue
public static CheckListValue Positive=> new CheckListValue
{
Text = "Positive",
Value = true
};
public static CheckListValue Negative=> new CheckListValue
{
Text = "Negative",
Value = false
};
public static CheckListValue Empty=> new CheckListValue
{
Text = "Empty",
Value = null
};
public static List<CheckListValue> All => new List<CheckListValue>
{
Positive, Negative, Empty
};
}
public class CheckListValue
{
public string Text { get; set; }
public bool? Value { get; set; }
}
And converter:
public class BoolNullableToCheckListValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var boolValue = value as bool?;
if (!boolValue.HasValue)
return CheckListValues.Empty;
return boolValue.Value ? CheckListValues.Positive : CheckListValues.Negative;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var checkListValue = value as CheckListValue;
return checkListValue?.Value;
}
}
ViewModel:
public List<CheckListValue> CheckListValueList => CheckListValues.All;
public CheckListProperties CheckListProperties { get; set; }
public override void Init(object initData)
{
//Here CheckListProperties takes from DB on every load of Page
}
public class CheckListProperties
{
public bool? PickerBool1 { get; set; }
public bool? PickerBool2 { get; set; }
public bool? PickerBool3 { get; set; }
}
When i'm choosing from picker it works good, changes bool correctly and displays text, but this is modification page and on load, i should see already chosen before values, but its not. Its empty.
Do you know why it could be? Because i have no idea.
Thank you in advance, guys!

How to use CalenderView in UWP MVVM

I want to bind the selected Calender View Item and set it to
a DateTime Variable.
My CalenderView Xaml looks like:
<CalendarView Grid.Row="6" Grid.ColumnSpan="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20"/>
I have an DateTime item in the Datacontext class:
private DateTime _DueDate;
public DateTime DueDate
{
get { return this._DueDate; }
set
{
if (this._DueDate != value)
{
this._DueDate = value;
base.PropertyOnChanged("DueDate");
}
}
}
And the DateTimeConverter:
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
DateTime date = ((DateTime)value);
return date.Day + "." + date.Month + "." + date.Year;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return DateTime.Parse((string)value);
}
}
Here is also the Doc to the Calender View:
CalenderView MSDN
In the Docs is a Property SelectedDate, but I only see in the XAML SelectedDateChanged EventHandler. But I want to do it in MVVM.
My Problem is I don´t know on which Property I can set the
Binding. I looked in the Doc but I only find the Date="" property
from the DatePicker but I don´t find anything to the CalenderView.
UPDATE
Following to the Comment from
#Juo Zuo:"CalendarView has a SelectedDates property. Usually, we can use this property to set the selected date like: MyCalendarView.SelectedDates.Add(new DateTime(2016, 5, 5));. However this property is read-only, we can't use it for binding. So, I'm afraid there is no way to set selected dates with Binding"
I would expand the Question.
My Question is:
Is there any way to use the Calender View with the MVVM Pattern from MSDN ?
All you need to do is to create an attached property and encapsulate the SelectedDates.Add logic within it.
public static class CalendarViewHelper
{
public static IList<DateTimeOffset> GetSelectedDates(DependencyObject obj)
{
return (IList<DateTimeOffset>)obj.GetValue(SelectedDatesProperty);
}
public static void SetSelectedDates(DependencyObject obj, IList<DateTimeOffset> value)
{
obj.SetValue(SelectedDatesProperty, value);
}
public static readonly DependencyProperty SelectedDatesProperty =
DependencyProperty.RegisterAttached("SelectedDates", typeof(IList<DateTimeOffset>), typeof(CalendarView),
new PropertyMetadata(null, (d, e) =>
{
var cv = d as CalendarView;
var dates = e.NewValue as IList<DateTimeOffset>;
if (cv != null && dates != null)
{
foreach (var date in dates)
{
cv.SelectedDates.Add(date);
}
}
}));
}
<CalendarView local:CalendarViewHelper.SelectedDates="{x:Bind Dates, Mode=OneWay}" />
If your Dates property has more than one items inside, make sure you change the SelectionMode to Multiple.

Images aren't displayed in listbox after binding

I am having an issue where in a listbox binding text is being displayed but none of the binding images are. I download and parse an xml file just fine and display the text I want but then want to show an image depending on the status. Linename and Service show OK but the binding image does not show at all. Atype is just used to call the GetImage method (not neat I know). It should then set the ImageSource according to the status but no image is shown at all.
XElement XmlTweet = XElement.Parse(e.Result);
var ns = XmlTweet.GetDefaultNamespace();
listBox1.ItemsSource = from tweet in XmlTweet.Descendants(ns + "LineStatus")
select new FlickrData
{
Linename = tweet.Element(ns + "Line").Attribute("Name").Value,
Service = tweet.Element(ns + "Status").Attribute("Description").Value,
Atype = GetImage(tweet.Element(ns + "Status").Attribute("Description").Value)
};
public String GetImage(String type)
{
FlickrData f = new FlickrData();
switch(type)
{
case "Good Service":
f.Type = new BitmapImage(new Uri("/Images/status_good.png", UriKind.Relative));
break;
case "Minor Delays":
f.Type = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
case "Severe Delays":
f.Type = new BitmapImage(new Uri("/Images/status_severe.png", UriKind.Relative));
break;
case "Planned Closure":
f.Type = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
}
return "anything";
}
In FlickrData it is a simple get set with the imagesource Type not displaying.
public class FlickrData
{
public string Linename { get; set; }
public string Service { get; set; }
public string Detail { get; set; }
public ImageSource Type { get; set; }
public string Atype { get; set; }
}
Converters come into handy in such situations.
First, your image in the XAML should be defined like this
<Image Source="{Binding Path=Atype, Converter={StaticResource AtypeToImageConverter}}" Width="100" Height="100"/>
Then create a converter class in the project. (Right click on project name -> select Add -> select Class )
Name the class as "AtypeToImageConverter"
public class AtypeToImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType != typeof(ImageSource))
throw new InvalidOperationException("The target must be an ImageSource");
BitmapImage result = null;
int type = value.ToString();
switch (type)
{
case "Good Service":
result = new BitmapImage(new Uri("/Images/status_good.png", UriKind.Relative));
break;
case "Minor Delays":
result = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
//other cases
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
and it will do the magic. You can remove the Type from your FlickrData class.
Any doubt, just google on how to use converters in C#

How is [DataMember] used with Image?

I have the following code in a WCF service:
[DataContract]
[KnownType(typeof(Bitmap))]
[KnownType(typeof(Image))]
public class CompositeType {
Image FImg = null;
public Image Picture {
get {
return FImg;
}
set {
FImg = value;
}
}
If I add [DataMember] to the public Image, then the Service Reference gets broken in another solution.
[DataMember]
public Image Picture{
get {
return FImg;
}
set {
FImg = value;
}
}
My question is how do I use [DataMember] and Image at the same time? I know I can use a byte array and am currently doing so and then formatting / converting it in the client that calls my service, but I'd rather bind to the Image instead of having to convert a byte array.
I've found that using the AutoGeneratingColumn event handle on the clientside (the Silverlight application calling my WCF service) works also. Not necessarily an answer to my question, but I think it's useful to know. I would've added as comment, but code is too long.
private void dgResults_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {
if (e.PropertyType == typeof(byte[])) {
e.Column.Header = e.Column.Header + "_D";
// Create a new template column.
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = e.Column.Header + "_E";
templateColumn.CellTemplate = (DataTemplate)Resources["imgTemplate"];
templateColumn.CellEditingTemplate = (DataTemplate)Resources["imgTemplate"];
// ...
// Replace the auto-generated column with the templateColumn.
e.Column = templateColumn;
}
}
The Resources["imgTemplate"] are created in the .XAML file in Silverlight and this code is in its code-behind.
<UserControl.Resources>
<local:BinaryArrayToURIConverter x:Key="binaryArrayToURIConverter" />
<DataTemplate x:Key="imgTemplate">
<Image x:Name="img" Source="{Binding GraphicBytes,Converter={StaticResource binaryArrayToURIConverter}}"/>
</DataTemplate>
</UserControl.Resources>
The local: refers to part of the main XAML declaration:
xmlns:local="clr-namespace:<your namespace here>"
The code for BinaryArrayToURIConverter:
public class BinaryArrayToURIConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
MemoryStream ms = new MemoryStream((byte[])value);
BitmapImage image = new BitmapImage();
image.SetSource(ms);
return image;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}

Categories