Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind with a StringFormat

Tags:

wpf

xaml

I have a ComboBox which I am binding to an IEnumerable<int> source.

The source has values like 12,13,14 but I want the ComboBox to display Version 12, Version 13, Version 14 etc with SelectedValue still 12, 13 and 14.

For now I am modifying the Source to add Version to it and then Binding the ComboBox to an IEnumerable.

XAML

    <ComboBox x:Name="ComboBoxVersions"  
              SelectedIndex="0" 
              SelectionChanged="ComboBoxVersions_OnSelectionChanged" 
              ItemsSource="{Binding EnvironmentVersions}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
like image 695
Charu Avatar asked Oct 17 '25 10:10

Charu


2 Answers

using ComboBox.ItemStringFormat:

<ComboBox ItemsSource="{Binding EnvironmentVersions}" 
          ItemStringFormat="version: {0}" />

or using ComboBox.ItemTemplate

<DataTemplate>
    <TextBlock Text="{Binding StringFormat=Version: {0}}" />
</DataTemplate>

or

<DataTemplate>
    <TextBlock>
        <Run Text="Version " />
        <Run Text="{Binding }"/>
    </TextBlock>
</DataTemplate>
like image 156
Liero Avatar answered Oct 19 '25 13:10

Liero


You could use something like this

 <TextBlock Text="{Binding StringFormat=Version: {0}}" />
like image 30
Marcin Avatar answered Oct 19 '25 13:10

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!