Dr Hund Dr Hund - 1 year ago 286
C# Question

Combobox binding and stringFormat

I have a WPF Combobox

<ComboBox SelectedValue="{Binding ElementName=Ctrl, Path=Day, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat='00'}"
ItemsSource="{Binding ElementName=Ctrl, Path=AvailableDays, Mode=OneWay, StringFormat='00'}"
IsEditable="True" Grid.Column="0" />

which is Databound to these Properties

public int? Day {
get { return _day; }
set {
if (_day != value) {
_day = value;

public IEnumerable<int> AvailableDays {
get { return _availableDays ?? (_availableDays = Enumerable.Range(1, 31)); }

Binding works. But my issue is the Formating of the values. I want days<10 to be formated with a leading zero. But my "StringFormat='00'" is completly ignored, which is odd because the same format works with a textblock without a problem.

Answer Source

Binding.StringFormat works only if target property type is string. This is why it works with string TextBlock.Text, but doesn't work with object ComboBox.SelectedValue. Generally, if you want to format the result of a binding, you can create a custom StringFormatConverter : IValueConverter class with trivial implementation and use it in Binding.Converter.

In your case, you should use ComboBox.ItemStringFormat instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download