【问题标题】:How to have window size itself to longest string如何将窗口大小本身设置为最长的字符串
【发布时间】:2024-01-22 00:55:01
【问题描述】:

我正在向我的应用程序添加一个新窗口。此应用程序包含一个ListBox,其ItemsSource 属性绑定到视图模型对象的ObservableCollection。这是用于渲染视图模型对象的数据模板:

<DataTemplate x:Key="DomainTemplate" DataType="DomainViewModel">
    <Border BorderBrush="{Binding Converter={StaticResource BrushConverter}, Path=IsSelected}"
            BorderThickness="2"
            Margin="5"
            Name="SelectedBorder">
        <Button Click="SelectDomain_Click"
                Content="{Binding Path=Name}"
                FontSize="16"
                FontWeight="Bold"
                Height="60"
                IsEnabled="{Binding Path=CurrentSiteIsValid, RelativeSource={RelativeSource AncestorType={x:Type c:DomainPicker}}}"
                Margin="5" />
    </Border>
</DataTemplate>

我正在使用ListBox 上的HorizontalContentAlignment="Stretch" 设置来使所有Buttons 填充ListBox 的宽度。此外,视图模型对象是从数据库中读取的,并且 Name 属性可以包含最长 80 个字符的任何字符串。

问题是我希望Buttons 的宽度与Button 的宽度相同,如果它直接在窗口上,最长的标题将是。然后ListBox 应该调整自己的大小以包含Button,最后窗口应该调整自己的大小为ListBox

我怎样才能做到这一点?

【问题讨论】:

  • 你的最后一段有点不清楚。您能否发布您现在得到的结果的屏幕截图,以及您想如何更改它?

标签: wpf window size


【解决方案1】:

要使Button 控件的长度相同,您可以在DataTemplate 中添加一个Grid.IsSharedSizeScope 属性设置为trueGrid。使用SharedSizeGroup 属性集定义一列:

<DataTemplate x:Key="DomainTemplate" DataType="DomainViewModel">
    <Grid Grid.IsSharedSizeScope="True">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
        </Grid.ColumnDefinitions>
        <Border BorderBrush="{Binding Converter={StaticResource BrushConverter}, 
Path=IsSelected}" BorderThickness="2" Margin="5" Name="SelectedBorder">
            <Button Click="SelectDomain_Click" Content="{Binding Path=Name}" 
FontSize="16" FontWeight="Bold" Height="60" IsEnabled="{Binding CurrentSiteIsValid, 
RelativeSource={RelativeSource AncestorType={x:Type c:DomainPicker}}}" Margin="5" />
        </Border>
    </Grid>
</DataTemplate>

要让Button 控件停止填充ListBox,请从中删除HorizontalAlignment="Stretch" 声明。

要使Window 大小适合内容,请将其SizeToContent 属性设置为WidthAndHeight,并从其声明中删除所有WidthHeight 属性。

告诉我进展如何。

【讨论】:

  • 您的代码几乎是正确的。我玩了一下,发现Grid.IsSharedSizeScope="True" 附加属性必须在ListBox 上,而不是DataTemplate 中的Grid。其他一切都是一样的。我遇到的唯一问题是ListBox 的宽度大于Buttons 的宽度。但那是因为标题让窗口太宽了
  • ListBox 放入宽度设置为AutoGrid 列?
  • ListBox 在网格中,但其宽度未设置为 Auto。就是现在。我还将标题留空并在标题栏下方的顶部放置一个绑定到标题的TextBlock。该窗口是应用程序的应用栏窗口,所以只有在应用程序运行时才会显示。
最近更新 更多