键入TextBox会导致ListBox宽度增加

时间:2015-11-03 08:51:27

标签: c# wpf layout textbox listbox

我有ListBox,Horizo​​ntalAlignment =“Left”所以列表框宽度取决于它的内容。每个列表框项中都有一个文本框。当我在文本框中键入时,列表框的宽度会增加。 我希望TextBox宽度取决于ListBox项目宽度,但反之亦然,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

更新 不接受的答案,但@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>

2 个答案:

答案 0 :(得分:0)

如果你想实现这个目标:

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>

答案 1 :(得分: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>