2015-06-04 128 views
0

是否有可能有ListBox(其中包含ScrollViewer默認)和ListBoxItemScrollViewer? 我想實現下一個視圖: enter image description hereWPF:ListBoxItem帶滾動條

而且這個ListBox還應該支持虛擬化。 (我知道如何啓用它,我只是想將它的工作,如果我使用2個滾動觀衆?)

更新: 我需要使用ListBox.ItemTemplate,因爲我結合ItemsSource

感謝您的提示。

+0

Scrollviewers是醜陋的。如何使用'TextWrapping'代替? –

+0

'TextWrapping'不合適。 –

回答

1

簡單。 (我已經給你三種方法來做到這一點,必須是正確的!)

通過XAML:

<ListBox x:Name="ListBoxControl" HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="520"> 
     <ListBoxItem Width="520"> 
      <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled"> 
       <Label Content="My Name is KidCode. This is a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaly long comment."/> 
      </ScrollViewer> 
     </ListBoxItem> 
    </ListBox> 

從C#:

namespace StackExchange 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      var lbv = new ListBoxItemSV() 
      { 
       Height = 40, 
       Width= 520, 
       Background = Brushes.Blue 
      }; 
      ListBoxControl.Items.Add(lbv); 
     } 

     public class ListBoxItemSV : ListBoxItem 
     { 
      ScrollViewer sv = new ScrollViewer() 
      { 
       HorizontalScrollBarVisibility = ScrollBarVisibility.Visible, 
       VerticalScrollBarVisibility = ScrollBarVisibility.Hidden 
      }; 
      Label lbl = new Label() 
      { 
       Content = "A really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long name." 
      }; 

      public ListBoxItemSV() 
      { 
       sv.Content = lbl; 
       this.Content = sv; 
      } 
     } 
    } 
} 

此結果在以下內容中:(我已經添加了一條簡短的評論,以便您可以看到差異,您可以使滾動條始終貫穿整個過程,但這僅僅是一個示例。)

ListBoxItem with ScrollViewer

如果您使用項目模板:(我從來沒有這樣做,所以如果它的錯誤不要拍我! :))

XAML:

<ListBox x:Name="ListBoxTwo"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled" Width="520"> 
         <Label Content="{Binding}"/> 
        </ScrollViewer> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

代碼背後:

List<string> Mylist = new List<string>(); 
    Mylist.Add("Short Name"); 
    Mylist.Add("Another Short Name"); 
    Mylist.Add("A massively, hugely, giganticly, monstorously large name. (Its even bigger than than you think...............) "); 

    ListBoxTwo.ItemsSource = Mylist; 

輸出:

Output

+0

謝謝,但我需要使用'ListBox.ItemTemplate',因爲我將項目綁定到'ListBox' –

+0

總是有助於在問題中包含這些類型的細節。 – KidCode

+0

@AnnaOsiatnik - 編輯我的答案。所有這三項工作,我相信最後一個是你想要的? – KidCode