连接string,而不是使用一堆TextBlocks

我想在WPF ItemsControl中显示Customer对象的列表。 我为此创build了一个DataTemplate:

<DataTemplate DataType="{x:Type myNameSpace:Customer}"> <StackPanel Orientation="Horizontal" Margin="10"> <CheckBox"></CheckBox> <TextBlock Text="{Binding Path=Number}"></TextBlock> <TextBlock Text=" - "></TextBlock> <TextBlock Text="{Binding Path=Name}"></TextBlock> </StackPanel> </DataTemplate> 

所以我想要的基本上是一个简单的列表(checkbox),其中包含NUMBER – 名称。 是不是有一种方法可以在绑定部分中直接连接数字和名称?

有StringFormat属性(在.NET 3.5 SP1),您可能可以使用。 和有用的WPF绑定作弊sheat可以在这里find。 如果它没有帮助,你可以写你自己的ValueConverter或自定义属性为您的对象。

刚刚检查,你可以使用多重绑定的StringFormat。 在你的情况下代码将是这样的:

 <TextBlock> <TextBlock.Text> <MultiBinding StringFormat=" {0} - {1}"> <Binding Path="Number"/> <Binding Path="Name"/> </MultiBinding> </TextBlock.Text> </TextBlock> 

我不得不开始格式与空间的string,否则Visual Studio将不会build立,但我认为你会find办法避开它:)

编辑
StringFormat中需要空格,以防止parsing器将{0}视为实际的绑定。 其他select:

 <!-- use a space before the first format --> <MultiBinding StringFormat=" {0} - {1}"> <!-- escape the formats --> <MultiBinding StringFormat="\{0\} - \{1\}"> <!-- use {} before the first format --> <MultiBinding StringFormat="{}{0} - {1}"> 

如果你想连接一个静态文本的dynamic值,试试这个:

 <TextBlock Text="{Binding IndividualSSN, StringFormat= '\{0\} (SSN)'}"/> 

显示 :234-334-5566(SSN)

看到我在我的代码中使用Run类中使用以下示例:

  <TextBlock x:Name="..." Width="..." Height="..." <Run Text="Area="/> <Run Text="{Binding ...}"/> <Run Text="sq.mm"/> <LineBreak/> <Run Text="Min Diameter="/> <Run Text="{Binding...}"/> <LineBreak/> <Run Text="Max Diameter="/> <Run Text="{Binding...}"/> </TextBlock > 

您也可以使用可绑定的运行。 有用的东西,尤其是如果你想添加一些文本格式(颜色,fontweight等)。

 <TextBlock> <something:BindableRun BoundText="{Binding Number}"/> <Run Text=" - "/> <something:BindableRun BoundText="{Binding Name}"/> </TextBlock> 

这是一个原创的课程:
这是一些额外的改进。
这就是所有的代码:

 public class BindableRun : Run { public static readonly DependencyProperty BoundTextProperty = DependencyProperty.Register("BoundText", typeof(string), typeof(BindableRun), new PropertyMetadata(new PropertyChangedCallback(BindableRun.onBoundTextChanged))); private static void onBoundTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((Run)d).Text = (string)e.NewValue; } public String BoundText { get { return (string)GetValue(BoundTextProperty); } set { SetValue(BoundTextProperty, value); } } public BindableRun() : base() { Binding b = new Binding("DataContext"); b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(FrameworkElement), 1); this.SetBinding(DataContextProperty, b); } }