Wpf 如何使用StringFormat进行绑定
我有一个Wpf 如何使用StringFormat进行绑定,wpf,xaml,Wpf,Xaml,我有一个组合框,绑定到IEnumerable源 源代码有12,13,14这样的值,但我希望组合框显示版本12、版本13、版本14等,其中SelectedValue仍然是12、13和14 目前,我正在修改源代码以向其添加版本,然后将ComboBox绑定到IEnumerable XAML <ComboBox x:Name="ComboBoxVersions" SelectedIndex="0" SelectionChange
组合框
,绑定到IEnumerable
源
源代码有12,13,14这样的值,但我希望组合框
显示版本12、版本13、版本14等,其中SelectedValue仍然是12、13和14
目前,我正在修改源代码以向其添加版本,然后将ComboBox绑定到IEnumerable
XAML
<ComboBox x:Name="ComboBoxVersions"
SelectedIndex="0"
SelectionChanged="ComboBoxVersions_OnSelectionChanged"
ItemsSource="{Binding EnvironmentVersions}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
您可以使用类似的东西
<TextBlock Text="{Binding StringFormat=Version: {0}}" />
这里有一个简单的方法:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Version " />
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
由于ItemTemplate
仅定义项目的显示方式,因此组合框的SelectedItem
属性仍然保留版本号集合中的原始值。您可以在数据模板中的绑定中添加字符串格式
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding StringFormat=Version {0}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
使用ComboBox.ItemStringFormat:
<ComboBox ItemsSource="{Binding EnvironmentVersions}"
ItemStringFormat="version: {0}" />
或者使用ComboBox.ItemTemplate
<DataTemplate>
<TextBlock Text="{Binding StringFormat=Version: {0}}" />
</DataTemplate>
或
OP明确希望“SelectedValue仍然为12、3和14”,这与此解决方案不起作用。@Marcin这根本不起作用。我确实试过了,但它仍然显示了12、13、14这只是一个例子。我试图向您展示如何将StringFormat与静态文本结合使用。当然,我犯了一个错误。您应该在文本块中使用它。我更新我的回答对IEnumerable
没有影响,因为字符串格式可以与string
s绑定,而不是int
s绑定。只有ItemStringFormat
可以在IEnumerable
列表上工作。另外两个失败了。
<DataTemplate>
<TextBlock>
<Run Text="Version " />
<Run Text="{Binding }"/>
</TextBlock>
</DataTemplate>