2015-02-24 26 views
0

我有一個ListBox設置爲自動編號,如下所示。我想在每個ListBoxItem的前面格式化數字,以便所有行中的數字都相互正確對齊。我想我可以使用項目數來確定索引中有多少個字符,使用該信息在我的視圖模型中設置一個格式,並綁定到它。不幸的是,我甚至沒有想出如何爲我的數字格式化一個常量字段寬度。列表框將內容排列好看很多。所以我需要知道如何設置格式,以便我可以綁定它。需要在WPF列表框中格式化自動編號的行

  <ListBox ItemsSource="{Binding Profiles}" SelectedItem="{Binding SelectedProfile, Mode=TwoWay}" 
        AlternationCount="{Binding Path=Profiles.Count}"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal"> 
          <TextBlock Margin="0,0,5,0" 
           Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}"/> 
          <TextBlock Text="{Binding}" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

回答

0

Profile型應該有某種形式的,你應該設置的Index財產。 AlternationCount「使交替容器具有獨特的外觀」,所以我相信你沒有正確使用它。當你有一個屬性添加到您的Profile類型,那麼你可以爲你的ItemTemplate喜歡做一些事情:

<DataTemplate> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="100"> 
      <ColumnDefinition /> 
     </Grid.ColumnDefinitions> 
     <TextBlock HorizontalAlignment="Right" 
        Margin="0 0 5 0" 
        Grid.Column="0" 
        Text="{Binding Index}"/> 
     <TextBlock Grid.Column="1" 
        Text="{Binding}" /> 
    </Grid> 
</DataTemplate> 
+0

這將工作。我只是將列寬設置爲可以顯示4位整數的東西。 – spainchaud 2015-02-24 21:17:37

+0

@spainchaud是的,列寬是一個單獨的問題。您可以使用填充,或者您可以選擇始終使用固定寬度的字體(即0001,0002,...,9999)顯示4個字符,或者可以在完成綁定後計算大小,並根據字符數。有多種選擇可供選擇。 – Kcvin 2015-02-24 21:25:07