【问题标题】:WPF Grid change ColumnSpan on MinWidthWPF Grid 在 MinWidth 上更改 ColumnSpan
【发布时间】:2019-01-26 10:05:52
【问题描述】:

假设我有一个 4 列的网格。每列采用相同的宽度

-> 100% / 4cols = 25%。

第 3 列包含 TextBlock 或任何其他控件。现在,当我调整WindowWidth 的大小并且column 变为minimum value 时,我希望TextBlock 使用ColumnSpan="2",否则TextBlock 将太小。我希望你们明白我的意思。我尝试了很多东西,但我什至没有接近我想要的,因为我对WPF 很陌生。例如,设置minWidth 使其不会变得太小是行不通的,因为在某些时候控件仍将隐藏在网格列中。我没有任何有用的xaml 给你,除非你只想要网格布局。也许Grid 不是我想要的正确的东西?其他布局似乎不适合此目的。任何帮助表示赞赏。

【问题讨论】:

  • 可以添加 UI 代码吗?

标签: c# wpf layout grid


【解决方案1】:

您可以处理Grid 或窗口的SizeChanged 事件,并在网格/窗口缩小到预定义的最小宽度以下时以编程方式设置TextBlockGrid.ColumnSpan 附加属性。请参考以下示例代码。

private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
    const double MinWidth = 200;
    Grid grid = (Grid)sender;
    if (grid.ActualWidth < MinWidth)
        Grid.SetColumnSpan(textBlock, 2);
    else
        Grid.SetColumnSpan(textBlock, 1);
}

XAML:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid SizeChanged="Grid_SizeChanged">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="25*" />
            <ColumnDefinition Width="25*" />
            <ColumnDefinition Width="25*" />
            <ColumnDefinition Width="25*" />
        </Grid.ColumnDefinitions>
        <TextBlock Background="Yellow" Text="1" />
        <TextBlock Background="Green" Text="2" Grid.Column="1" />
        <TextBlock Background="Red" Text="4" Grid.Column="3"  />
        <TextBlock x:Name="textBlock" Background="Blue" Text="3" Grid.Column="2" Grid.ColumnSpan="2" />
    </Grid>
</Window>

如果您减小窗口的宽度,蓝色的TextBlock 会延伸到第三和第四列。

【讨论】:

  • 这正是我想要的。仅在 xaml 中这样做会很好,但我想这是不可能的,或者至少不是很容易。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2018-03-23
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
相关资源
最近更新 更多