【问题标题】:How can I append two properties together in a listbox?如何在列表框中将两个属性附加在一起?
【发布时间】:2014-09-14 15:00:56
【问题描述】:

我有两个属性,例如日期和号码。我有一个列表框,当前一个接一个地绑定它们,所以现在两个属性占用了两行。我怎样才能将它们一一排列? xaml 不允许我将两个属性绑定到一个文本块。

这就是我的列表框现在的样子:

号码 日期

我希望它看起来像:

编号日期

我的列表框代码如下所示:

<ListBox HorizontalAlignment="Left" Margin="78,35,0,-32" Grid.Row="1" Width="300" ItemsSource="{Binding ListOfItems}" Grid.RowSpan="3" >
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Number}" />
                                <TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yy}}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

【问题讨论】:

    标签: c# wpf xaml data-binding listbox


    【解决方案1】:

    您可以使用运行将多个属性绑定到一个文本块

     <TextBlock>
           <Run Text="{Binding Number}"></Run>
           <Run Text="{Binding Date, StringFormat={}{0:MM/dd/yy}}"></Run>
     </TextBlock>
    

    多重绑定

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

    【讨论】:

    • 谢谢,这样效果最好。我使用了 Run,它在两个属性之间留出了一个空格。非常感谢!!
    【解决方案2】:

    如果我理解正确,您需要在 StackPanel 中使用水平方向。将您的 DataTemplate 更改为以下之一:

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Number}" />
        <TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yy}}" />
    </StackPanel>
    

    【讨论】:

    • 哇,我不知道,如何在数字和日期之间留一个空格,以便阅读更清晰可见?谢谢。
    • 在 TextBlock 上使用左/右边距或添加另一个带有空格的 TextBlock。
    • 根据您的需要,您可以在数据上创建另一个属性,该属性使用 String.Format 连接成一个新字符串,并绑定到该字符串。还可以考虑使用@Heena Patil 的答案。
    【解决方案3】:

    您可能希望StackPanel 水平堆叠项目:Orientation="Horizontal"

    (参见http://wpftutorial.net/StackPanel.htmlhttp://msdn.microsoft.com/en-us/library/ms752328(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多