Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何使用StringFormat进行绑定_Wpf_Xaml - Fatal编程技术网

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>