在 TextBox 中键入会导致 ListBox 宽度增加

Typing into TextBox leads ListBox width increasing

我有带 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>

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

如果你想实现这个:

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>
<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>