wpf - ComboBox.Text 未考虑 ItemStringFormat 属性

标签 wpf xaml binding

我刚刚注意到一个看起来像错误的奇怪行为。考虑以下 XAML:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Page.Resources>
    <x:Array x:Key="data" Type="{x:Type sys:String}">
        <sys:String>Foo</sys:String>
        <sys:String>Bar</sys:String>
        <sys:String>Baz</sys:String>
    </x:Array>
  </Page.Resources>
  <StackPanel Orientation="Vertical">
      <Button>Boo</Button>
      <ComboBox Name="combo" ItemsSource="{Binding Source={StaticResource data}}" ItemStringFormat="##{0}##" />
      <TextBlock Text="{Binding Text, ElementName=combo}"/>
  </StackPanel>
</Page>

ComboBox 将值显示为“##Foo##”、“##Bar##”和“##Baz##”。但是 TextBlock 将所选值显示为“Foo”、“Bar”和“Baz”。因此 ItemStringFormat 显然被 Text 属性忽略了...

这是一个错误吗?如果是,是否有解决方法?
还是我只是做错了什么?

最佳答案

这不是错误:ItemStringFormat 只是“具有文本 block 的数据模板绑定(bind)到具有绑定(bind)中设置的指定字符串格式的值”的快捷方式。然而,Text 通常在 IsEditable 为真且表示用户输入时使用。当您的列表中有除字符串以外的任何内容时,最好使用 SelectedItem 而不是 Text。在任何情况下,以下代码都会将格式重新应用到文本:

<TextBlock Text="{Binding ElementName=combo, Path=Text, StringFormat='##{0}##'}"/>

关于wpf - ComboBox.Text 未考虑 ItemStringFormat 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2847443/

相关文章:

c# - 在 WPF 中使用 ViewModel 创建 UserControl

c# - 在绑定(bind)到 ICommand 的 Button 处控制 ExceptionValidationRule

c# - GridUnitType.Star?

c# - 添加拖放行为

c# - WPF转换器在文本更改时实时更新文本框的背景颜色

xaml - ListView xaml uwp 中缺少垂直滚动

c# - WPF 用户控件中的多个内容展示器

触摸屏平板电脑上的 WPF 滚动查看器

c# - 绑定(bind)到 ViewModel 和 CodeBehind 中的属性

binding - JAXB XJC 两个声明导致冲突。无法兑现自定义绑定(bind)