简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM