2015-11-03 77 views
1

我有ListBox与Horizo​​ntalAlignment =“左”,所以列表框的宽度取决于它的内容。每个列表框项目中都有一个文本框。当我在文本框中输入时,列表框的宽度增加。 我希望文本框的宽度取决于列表框的项目宽度,但反之亦然,并且文本框中的文本被包装。键入到TextBox引线列表框宽度增加

<Window x:Class="WpfOverflow.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="1000"> 
<ListBox Background="CadetBlue" HorizontalAlignment="Left" MaxWidth="500"> 
    <ListBox.Items> 
    <ListBoxItem> 
     <DockPanel> 
     <TextBlock Text="Some text of the element" DockPanel.Dock="Top"/> 
     <TextBox Text="Enter text here" TextWrapping="WrapWithOverflow"/> 
     </DockPanel> 
    </ListBoxItem> 
    </ListBox.Items> 
</ListBox> 

Initial width of the list box ListBox width grows on typing

UPDATE: 不受@bathineni接受的答案,但答案帮助在这种情况下 Prevent a TextBox from horizontal expanding in WPF

<ListBox Background="CadetBlue" HorizontalAlignment="Left" MaxWidth="500" HorizontalContentAlignment="Stretch"> 
    <ListBox.Items> 
    <ListBoxItem> 
     <DockPanel> 
     <TextBlock Text="==== Some text of the element =====" DockPanel.Dock="Top"/> 
     <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled" Name="scv" > 
      <TextBox Text="Enter text here" Style="{StaticResource textBoxMultiline}" MaxWidth="{Binding ElementName=scv, Path=ActualWidth}" HorizontalAlignment="Stretch" /> 
     </ScrollViewer> 
     </DockPanel> 
    </ListBoxItem> 
    </ListBox.Items> 
</ListBox> 
+0

这难道不是简单地在你的'ListBoxItem'定义'Width'的情况下? –

+0

我不想固定宽度,宽度取决于列表框项目顶部的元素,由“元素的某些文本”表示,这部分宽度取决于用户数据。 –

回答

0
<ListBox Background="CadetBlue" HorizontalAlignment="Left" MaxWidth="500" Width="200" > 
     <ListBox.Items> 
      <ListBoxItem> 
       <DockPanel> 
        <TextBlock Text="Some text of the element" DockPanel.Dock="Top"/> 
        <TextBox Text="Enter text here" TextWrapping="NoWrap" Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth}" /> 
       </DockPanel> 
      </ListBoxItem> 
     </ListBox.Items> 
    </ListBox> 
+0

这种没有文字环绕的解决方案也很好 –

0

如果w ^蚂蚁实现这一点:

example wpf image

简而言之MaxWidth您ListBoxItem中。

<ListBox Background="CadetBlue" HorizontalAlignment="Left"> 
     <ListBox.Items> 
      <ListBoxItem MaxWidth="150"> 
       <DockPanel> 
        <TextBlock Text="Some text of the element" DockPanel.Dock="Top"/> 
        <TextBox Text="Enter text here" TextWrapping="WrapWithOverflow"/> 
       </DockPanel> 
      </ListBoxItem> 
     </ListBox.Items> 
    </ListBox> 
+0

我不想固定宽度,宽度取决于列表框项目顶部的元素,由“元素的某些文本”表示,这部分宽度取决于用户数据。如果用户数据小于150pt,那么它将增长到150pt。 –