【问题标题】:XAML string format in multibinding w/converter带转换器的多重绑定中的 XAML 字符串格式
【发布时间】:2016-10-05 11:21:14
【问题描述】:

我正在实现这个 TextBlock 并且 stringformat 没有出现,只有绑定属性的值。你能告诉我我做错了什么吗?

XAML 代码

<TextBlock>
     <TextBlock.Text>
       <MultiBinding Converter="{StaticResource ResourceKey=myConverter}">
         <Binding Path="loc.country" StringFormat="Country: {0}"/>
         <Binding Path="loc.area" StringFormat="Area: {0}"/>
       </MultiBinding>
     </TextBlock.Text>
 </TextBlock>

转换器

public class MyMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[1] == null)
            return values[0];

        return values[1];
    }

    public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

最好的问候,

【问题讨论】:

  • 检查输出窗口是否有绑定错误。
  • 没有绑定错误 Mike。

标签: c# wpf xaml binding


【解决方案1】:

请参阅 MSDN 上StringFormat 页面上的备注部分:

...

当您使用 MultiBinding 时,StringFormat 属性适用 仅当它设置在 MultiBinding 上时。 StringFormat 的值 在任何子 Binding 对象上设置的设置都将被忽略。 ...

原因是StringFormat 仅在绑定的目标属性实际上是string 类型时应用,而在MultiBinding 中不是这种情况


因此,您要么设置 MultiBinding 的 StringFormat(并且不设置其 Converter),要么在转换器中进行格式化。

【讨论】:

  • 感谢您的回答。就我而言,我想展示一个或另一个......如果第一个是国家,第二个是一个地区。你会推荐什么? (这也发生在其他地方,但为了简单起见,我没有把它放在这里)
  • 你总是可以从转换器返回一个格式化的字符串。
  • 完成。我已经按照你的建议做了。谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多