问题描述
我试图用结合上的StringFormat显示一些标签与MultiBinding。
I am trying to display some label with MultiBinding with Binding on StringFormat.
像这样:
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{Binding LabelStringFormat, Source={DynamicResource Texts}}">
<Binding Path="Lib1" />
<Binding Path="Lib2" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
LabelStringFormat能像[{0} / {1}]或类似的东西。它在构建已知,但必须从资源使用。
LabelStringFormat can be something like "[{0}/{1}]" or something like that. It is known in build but must be used from Resource.
但是,当我使用类似code以上,我得到错误:
But when I use something like code above, I get error:
A 'Binding' cannot be set on the 'StringFormat' property of type 'MultiBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
我可以使用绑定的内容,并在视图模型创建的字符串,但它是被忽视的时候有更多的标签,像这样的。
I can use binding on Content and create string in ViewModel, but it is unnoticed when there is more labels like this one.
谢谢
的Jakub
ThanksJakub
解决方案:
使用转换器:
public class StringMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return string.Format(values.Last() as string, values);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在WPF添加到转换资源:
In WPF add convertor to Resources:
<UserControl.Resources>
<ResourceDictionary>
<myComponents:StringMultiValueConverter x:Key="stringMultiValueConverter"/>
</ResourceDictionary>
</UserControl.Resources>
在添加标签:
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource stringMultiValueConverter}">
<Binding Path="Lib1" />
<Binding Path="Lib2" />
<Binding Path="LabelStringFormat" Source="{Dynamic Texts}"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
这工作的时候字符串格式是Multibinding的最后一个参数。
This work when string format is last param of Multibinding.
推荐答案
只需添加LabelStringFormat作为一个参数多绑定:
Just add the "LabelStringFormat" as a parameter of the multi-binding:
<MultiBinding>
<Binding Path="Lib1" />
<Binding Path="Lib2" />
<Binding Path="LabelStringFormat" Source="{DynamicResource Texts}" />
</MultiBinding>
使用您的IValueConverter执行格式化的String.Format((字符串)值[2],值[0],价值[1])
。
这篇关于与绑定的StringFormat MultiBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!