Silverlight date format using users locale? - silverlight

Is there a way to force Silverlight to use the users locale settings when presenting dates in a datagrid?
JD.

You could use a converter which looks at the System.Globalization.CultureInfo.CurrentCulture
public class SmartDateConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
DateTime date;
culture = System.Globalization.CultureInfo.CurrentCulture;
if (value != null && DateTime.TryParse(value.ToString(), out date))
{
string strDate = string.Empty;
strDate = date.ToString(culture.DateTimeFormat.ShortDatePattern.ToString());
return strDate;
}
return null;
}

Refer to the answer of this StackOverflow question:
How to change date format in Silverlight DatePicker control?

Related

Silverlight: Sorting a column that's bound with an IValueConverter?

I have a silverlight datagrid and am dynamically adding the columns to it programmatically.
One of the columns is bound to a complex property which is a List of business objects.
In order to display the correct property on the right object in the list I'm using a custom value converter, passing in the List and the object's name as an optional parameter.
I'm then spinning through the list, and finding the correct object in the list to bind to its value property.
This works perfectly for display purposes, but it seems that it disables or messes up prohibits the sorting of the column.
I know it has to do specifically with the converter because any other dynamic column that I'm adding, with a standard property binding, it sorts fine.
Here is the code of my IValueConverter:
public class MetaDataValueConverter : IValueConverter
{
public MetaDataValueConverter()
{
}
public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string result = string.Empty;
List<XFerMetadata> md = (List<XFerMetadata>)value;
foreach(XFerMetadata val in md)
{
if (val.Name.Match(parameter.ToString()))
{
result = val.Value;
break;
}
}
return result;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
And here is the code where I'm dynamically creating the column and setting the binding.
DataGridTextColumn col = new DataGridTextColumn();
col.Header = schema.FieldName;
Binding binding = new Binding("MetaData");
binding.Converter = new MetaDataValueConverter();
binding.ConverterParameter = schema.FieldName;
col.Binding = binding;
cols.Add(col);

Silverlight 4 DataGrid edit null value's cell

I'm creating a DataGrid where I set ItemsSource of the grid to a WCF request result. I have some null values for some strings, and I want to be able to enter values for those null values. I have no problems editing/saving pre-populated non-null values, but I can't modify the values of cells which have been returned as null. How can I achieve this?
You can use a Converter in your Binding that converts the null value to an empty string. Here is some code for the converter:
public class NullToEmptyStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? string.Empty : value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == string.Empty ? null : value;
}
}

WPF user control to display years and months from one total months value

I have a value in a database that is the totals number of months. In my WPF UI I need to display and update this value as the number of years and the number of months. I am struggling to get the bindings to work in this control so that I can view and update this one value of total months using the two separate textboxes (years and months)
Can anyone help with this?
In the class that is the source of your bindings (e.g. a ViewModel) you can add two properties that calculate the two values whenever needed. For example:
private const int MonthsInAYear = 12; // pedagogic purposes only :)
// This field contains the updated database value
private int _timeInMonths;
public int TimeYears
{
get { return _timeInMonths / MonthsInAYear; }
}
public int TimeMonths
{
get { return _timeInMonths % MonthsInAYear; }
}
If you want these values to be automatically updated, make this class implement the INotifyPropertyChanged interface and raise the PropertyChanged event for both properties whenever the value of _timeInMonths changes.
I guess you should use a converter to convert your month value to the corresponding Year and month values.Or you can do it in your viewmodel itself
Sample
public class MonthConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(((string)parameter)=="Year")
{
return (int)value / 12;
}
if (((string)parameter) == "Month")
{
return (int)value % 12;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
and in your xaml
<StackPanel Orientation="Horizontal">
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Year',StringFormat={}{0}Years}"/>
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Month',StringFormat={}{0}Months}"/>
</StackPanel>

How to set the default value of DateTime to empty string?

I have a property called Raised_Time, this property shows the time at which alarm is raised in datagrid Cell. I don't want to show anything in the datagrid cell when user creates any alarm, it just display the empty cell.
I googled in the internet and found that the default value of DateTime can be set using DateTime.MinValue and this will display MinValue of datetime i:e "1/1/0001 12:00:00 AM".
Instead I want that the datagrid cell remain blank until alarm is raised, it don't show any time.
I think datatrigger can be written in this case. I am not able to write the datatrigger for this scenario. Do I need a converter also that checks if DateTime is set to DateTime.MinValue the leave the datagrid cell blank??
Please help!!
I would use a Converter for this because it's something I can easily see reusing in the future. Here's one I used to use that took a string value of the DateFormat as the ConverterParameter.
public class DateTimeFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((DateTime)value == DateTime.MinValue)
return string.Empty;
else
return ((DateTime)value).ToString((string)parameter);
}
public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
I see two easy options to solve this:
You use the Nullable data type DateTime?, so that you can store null instead of DateTime.MinValue if the alarm time is not set.
You can use a converter, here is an example.
How about just changing your property to link to a private field of DateTime e.g.:
public string Raised_Time
{
get
{
if(fieldRaisedTime == DateTime.MinValue)
{
return string.Empty();
}
return DateTime.ToString();
}
set
{
fieldRaisedTime = DateTime.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
}
}
I use a nullable datetime for this, with an extension method like:
public static string ToStringOrEmpty(this DateTime? dt, string format)
{
if (dt == null)
return string.Empty;
return dt.Value.ToString(format);
}

Problem with binding Nullable value to WPF ComboBox

I am binding a WPF ComboBox to a nullable property of type MyEnum? (where MyEnum is an enumerated type)
I am programmatically populating the ComboBox items like this:
// The enum type being bound to
enum MyEnum { Yes, No }
// Helper class for representing combobox listitems
// (a combination of display string and value)
class ComboItem {
public string Display {get;set}
public MyEnum? Value {get;set}
}
private void LoadComboBoxItems()
{
// Make a list of items to load into the combo
var items = new List<ComboItem> {
new ComboItem {Value = null, Display = "Maybe"},
new ComboItem {Value = MyEnum.Yes, Display = "Yes"},
new ComboItem {Value = MyEnum.No, Display = "No"},};
// Bind the combo's items to this list.
theCombo.ItemsSource = items;
theCombo.DisplayMemberPath = "Display";
theCombo.SelectedValuePath = "Value";
}
Also in the code-behind, I am setting the DataContext to an instance of a class with a property called TheNullableProperty (for this example anyway) of type MyEnum?.
The binding of theCombo's SelectedValue is done in my XAML file.
<ComboBox
Name="theCombo"
SelectedValue="{Binding Path=TheNullableProperty,
UpdateSourceTrigger=PropertyChanged}"/>
Problem:
When the value of the bound property is initially non-null, the combo box displays the value properly.
But when the value of the bound property is initially null, the combo box is blank.
It looks like every aspect of data binding is working apart from the representation of the null value when the combobox is first shown.
For example: you can select Maybe from the dropdown, and the bound property is correctly set to null. It's just that initial loading that's failing. Maybe I need to just manually set the SelectedValue initially...
What I Ended Up Doing
Add a hidden textblock databound to the underlying nullable enum value via a Converter that converts from the nullable enum to a string (enum.ToString, or "null").
Load up the combo box with 'ComboItems' each having a string Label (displayed in the combo) and a string Value equal to the enum values as strings (and "null" for the null value).
Data-bind the combo box to the textblock.
/// <summary>
/// Convert from EnumeratedType? to string (null->"null", enum values->ToString)
/// </summary>
public class EnumConverter<T> : IValueConverter where T:struct
{
public static string To(T? c)
{
if (c == null)
return "null";
return c.ToString();
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return To((T?)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = (string) value;
if (s == "null")
return null;
return (T?)Enum.Parse(typeof(T), s);
}
}
public class MyEnumConverter : EnumConverter<MyEnum>
{
}
public class ComboItem
{
public string Value { get; set; }
public string Label { get; set; }
public ComboItem(MyEnum? e, string label)
{
Value = MyEnumConverter.To(e);
Label = label;
}
}
static IEnumerable<ComboItem> GetItems()
{
yield return new ComboItem(null, "maybe");
yield return new ComboItem(MyEnum.Yes, "yup");
yield return new ComboItem(MyEnum.No, "nope");
}
private void SetupComboBox()
{
thecombo.ItemsSource = GetItems().ToList();
}
You cannot bind to a null value by design in WPF (at least 3.5 SP1). This means that at the moment Source gets a Null as a value your Binding will be automatically broken and won't work even if you specify a valid value for the Source. You need to provide some "heart beating" mechanism for your binding via Value Converter. So that Converter transforms null value to some "Undefined" (non-null) for the Targets and than is able to convert your "Undefined" back to null...
There seem to be many issues with having null be a valid value for a ComboBox or ListBox, as similar questions have been asked here, here and here.
There hasn't been a superb, ogre-slaying answer to any of those.
My own suggestion is to add Maybe as a member of MyEnum. I know it's just an example but if everything with a MyEnum has it as nullable, then maybe MyEnum should have an Undefined member (or something similar), this is pretty common with enums anyway.
I found this solution online, which I think is pretty deck. I don't fully understand the implementation -- it's some pretty serious .NET kung fu -- but it's great from my perspective as a user. Give it a try:
http://philondotnet.wordpress.com/2009/09/18/how-to-select-null-none-in-a-combobox-listbox-listview/
DependencyProperty.UnsetValue Field
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace MyConverters
{
[ValueConversion(typeof(DateTime), typeof(String))]
public class StringToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int number;
return int.TryParse(value.ToString(), out number) ? number : DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString();
}
}
}
Here's a veryy simple solution to this problem:
Instead of having an item with a value of null in your ItemsSource, use DbNull.Value as item or as the item's value property.
I described this approach in detail here: https://stackoverflow.com/a/44170898/6713814

Resources