Problem with binding Nullable value to WPF ComboBox - wpf

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

Related

How to change formatting on specific cells in RadGridView

So I have a dynamic RadGridView. This means that I add Columns programmatically to the control. basically like this:
for (int i = 0; i < length; i++)
{
Binding b = new Binding(string.Format("Collection[{0}].ValueIWant", i));
binding.StringFormat = "{0:0.##}";
GridViewDataColumn column = new GridViewDataColumn()
{
Header = HeaderFor(i),
DataMemberBinding = b,
DataType = typeof(double?)
};
Control.columns.Add(column);
}
Now I need to add new lines that show the percentage between line 1 and 2, 2 and 3 and so on.
I've managed to do that but I'm not sure how I would manage to change the String.format specifically for those cells instead of the whole column.
CellTemplateSelector came to mind but I'm not sure that is a good idea as this might mean I have to set the binding again, not knowing the value of i and such. Also I only want to change the string.format on the binding.
As I'm manipulating the number as a double (0,5 is 50%, 50 is 5000%) I guess I have to mask the input as well. not sure if String.Format does that for me as well or if I should use RadMaskedInput
Use an IValueConverter to convert the column's value at each row to its appropriate representation. So for the binding on a computed column, use:
// bind to the row data itself, not any specific property
Binding b = new Binding();
b.Converter = new RowToFormattedValueConverter
This will send the complete row data to the converter; so you should be able to either use some existing property of the row to figure out which type it is (regular or percentage), or add an extra hidden property/column to specify it explicitly. The converter would then look something like this:
public class RowToFormattedValueConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var rowData = (MyModelType)value;
string formattedResult;
if (rowData.IsPerecentageRow)
{
formattedResult= string.Format("{0:P1}", rowData.ValueIWant);
}
else
{
formattedResult= string.Format("{0:0.##}", rowData.ValueIWant);
}
return formattedResult;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

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

what wrong with my binding convert?

I have some interface and class that contain List
public interface IListContain
{
Int32 ItemCount
{
get;
}
}
public class myStackPanel : StackPanel, IListContain
{
... // implimentation ...
}
I want to do binding between some TextBlock and the variable that 'point' on the object instance myStackPanel - so i wrote is in this way
XAML:
<TextBlock x:Name="ItemCount" FontSize="12" Text="{Binding ElementName=ListContainObject, Path=ItemCount,Converter={StaticResource IntConverter}}" />
The convert code ( int to string )
public class IntToStringConverter : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
{
return ( ( int )value ).ToString();
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
{
int result;
var succes = int.TryParse( ( string )value, out result );
return succes ? result : 0;
}
}
And on the cs file of the xaml i define in the constructor the
DataContext = this;
But still - nothing work !!!
I dont have fire convert event !!!
And i dont know what i did wrong.
Please help ...
Thanks.
( this code is in silverlight and the ListContainObject is not null ... its point on real object )
Can't say for sure without you showing us your implementation, but it's likely you've not used a dependency property for ItemCount / implemented INotifyPropertyChanged. Thus, WPF has no idea when the property is changing and the UI won't update accordingly (nor will your redundant converter).
Your using ElementName in your binding - this must resolve to the "name" field of an object listed in the xaml file - Im not sure from your code if thats the case. For example if you had in your xaml a ListBox control with name="my_listbox" then it would be fine for your binding to icnlude ElementName="my_listbox", but the way you describe it here Ive got a feeling your ListContainObject is declared somewhere in code behind?
You don't need a string converter when you bind an int sincer is done automatically. Probably your issue is that you don't have any element having x:Name="ListContainObject"

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

WPF Binding with invalid value for source

I have a TextBox that binds to an integer property.
What can I do so that when there is nothing no valid text in the TextBox that the property gets set to 0.
Really I think this can be extended so that if the binding fails then we set the source to default(T).
I need a nudge in the right direction.
TargetNullValue is the opposite of what I'm looking for(I think), that sets the TextBox text when the source is null. I want when the TextBox text is an invalid binding value to set the source as its default.
Applying a Converter such as the following to your binding should do the trick:
public class TextConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
int actual = (int)value;
return actual.ToString();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
string actual = (string)value;
int theValue = 0;
int.TryParse(actual, out theValue);
return theValue;
}
}
Your TextBox binding would look something like this:
<TextBox Text="{Binding ... Converter={StaticResource convert}}"></TextBox>
With the convertor defined as a resource of your Window/Control/...

Resources