我想在 WPF ItemsControl 中显示 Customer 对象的列表。我为此创建了一个数据模板:
<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>
所以我基本上想要的是一个包含数字 - 名称的简单列表(带有复选框)。有没有办法可以直接在 Binding 部分连接数字和名称?
最佳答案
您可能可以使用 StringFormat 属性(在 .NET 3.5 SP1 中)。有用的 WPF 绑定(bind)备忘可以找到 here 。 如果没有帮助,您始终可以为您的对象编写自己的 ValueConverter 或自定义属性。
刚刚检查过,您可以将 StringFormat 与多重绑定(bind)一起使用。在你的情况下,代码将是这样的:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat=" {0} - {1}">
<Binding Path="Number"/>
<Binding Path="Name"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
我必须以空格开始格式字符串,否则 Visual Studio 将无法构建,但我认为您会找到解决方法:)
编辑
StringFormat 中需要该空间,以防止解析器将 {0}
视为实际绑定(bind)。其他替代方案:
<!-- 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}">
关于.net - 连接字符串而不是使用一堆 TextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/541896/