sourcetip

WPF에서 그리드 제어에 경계를 설정하려면 어떻게 해야 합니까?

fileupload 2023. 4. 13. 21:06
반응형

WPF에서 그리드 제어에 경계를 설정하려면 어떻게 해야 합니까?

C#/WPF에서 그리드에 경계를 설정하려면 어떻게 해야 합니까?

이것이 제가 원하는 것입니다만, 어플리케이션의 그리드 컨트롤이 아닌 전체를 경계로 하고 있습니다.

<Grid>
    <Border BorderBrush="Black" BorderThickness="2">
        <Grid Height="166" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Width="479" Background="#FFF2F2F2" />
    </Border>
... and so on ...

외부 테두리만 원하는 경우 가장 쉬운 방법은 테두리 제어에 넣는 것입니다.

<Border BorderBrush="Black" BorderThickness="2">
    <Grid>
       <!-- Grid contents here -->
    </Grid>
</Border>

테두리가 완전히 채워지는 이유는 기본적으로 수평 정렬과 수직 정렬이 스트레치로 설정되어 있기 때문입니다.다음을 시도해 보십시오.

<Grid>
    <Border  HorizontalAlignment="Left" VerticalAlignment="Top"  BorderBrush="Black" BorderThickness="2">
        <Grid Height="166" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Width="479" Background="#FFF2F2F2" />
    </Border>
</Grid>

이것으로 원하는 것을 얻을 수 있습니다(단, 2개뿐만 아니라 4개 면 모두에 마진을 붙이고 싶을 수도 있습니다.

테두리 제어에 그리드를 중첩하는 경우

<Border>
    <Grid>
    </Grid>
</Border>

원하는 기능을 하지 않으면 원하는 기능을 수행하는 그리드(또는 테두리)에 대한 자체 제어 템플릿을 만들어야 합니다.

여백이 그리드가 아닌 테두리 태그에 명시되어야 한다는 것이 문제라고 생각합니다.

나중에 누구에게나 도움이 될 수 있는 답변입니다.난 그리드의 모든 사면을 둘러싸는 단순한 경계를 원했고 그렇게 해냈다...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...
<Grid x:Name="outerGrid">
    <Grid x:Name="innerGrid">
        <Border BorderBrush="#FF179AC8" BorderThickness="2" />
        <other stuff></other stuff>
        <other stuff></other stuff>
    </Grid>
</Grid>

이 코드 "innerGrid" 내에서 테두리를 바꿉니다.

비슷한 문제에 관심이 있지만 XAML을 사용하지 않는 경우 다음과 같은 해결책을 제시합니다.

var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);

이것이 나의 해결책입니다.당신에게 도움이 되길 바랍니다.

public class Sheet : Grid
{
    public static readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register(nameof(BorderBrush), typeof(Brush), typeof(Sheet), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderBrushChanged));

    public static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register(nameof(BorderThickness), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(1D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderThicknessChanged, CoerceBorderThickness));
    public static readonly DependencyProperty CellSpacingProperty = DependencyProperty.Register(nameof(CellSpacing), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(0D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnCellSpacingChanged, CoerceCellSpacing));

    public Brush BorderBrush
    {
        get => this.GetValue(BorderBrushProperty) as Brush;
        set => this.SetValue(BorderBrushProperty, value);
    }

    public double BorderThickness
    {
        get => (double)this.GetValue(BorderThicknessProperty);
        set => this.SetValue(BorderThicknessProperty, value);
    }

    public double CellSpacing
    {
        get => (double)this.GetValue(CellSpacingProperty);
        set => this.SetValue(CellSpacingProperty, value);
    }

    protected override Size ArrangeOverride(Size arrangeSize)
    {
        Size size = base.ArrangeOverride(arrangeSize);
        double border = this.BorderThickness;
        double doubleBorder = border * 2D;
        double spacing = this.CellSpacing;
        double halfSpacing = spacing * 0.5D;
        if (border > 0D || spacing > 0D)
        {
            foreach (UIElement child in this.InternalChildren)
            {
                this.GetChildBounds(child, out double left, out double top, out double width, out double height);

                left += halfSpacing + border;
                top += halfSpacing + border;
                height -= spacing + doubleBorder;
                width -= spacing + doubleBorder;

                if (width < 0D)
                {
                    width = 0D;
                }

                if (height < 0D)
                {
                    height = 0D;
                }

                left -= left % 0.5D;
                top -= top % 0.5D;
                width -= width % 0.5D;
                height -= height % 0.5D;

                child.Arrange(new Rect(left, top, width, height));
            }

            if (border > 0D && this.BorderBrush != null)
            {
                this.InvalidateVisual();
            }
        }

        return size;
    }
    
    protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);

        if (this.BorderThickness > 0D && this.BorderBrush != null)
        {
            if (this.CellSpacing == 0D)
            {
                this.DrawCollapsedBorder(dc);
            }
            else
            {
                this.DrawSeperatedBorder(dc);
            }
        }
    }

    private void DrawSeperatedBorder(DrawingContext dc)
    {
        double spacing = this.CellSpacing;
        double halfSpacing = spacing * 0.5D;


        #region draw border
        Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
        UIElementCollection children = this.InternalChildren;
        foreach (UIElement child in children)
        {
            this.GetChildBounds(child, out double left, out double top, out double width, out double height);
            left += halfSpacing;
            top += halfSpacing;
            width -= spacing;
            height -= spacing;

            dc.DrawRectangle(null, pen, new Rect(left, top, width, height));
        }
        #endregion
    }

    private void DrawCollapsedBorder(DrawingContext dc)
    {
        RowDefinitionCollection rows = this.RowDefinitions;
        ColumnDefinitionCollection columns = this.ColumnDefinitions;
        int rowCount = rows.Count;
        int columnCount = columns.Count;
        const byte BORDER_LEFT = 0x08;
        const byte BORDER_TOP = 0x04;
        const byte BORDER_RIGHT = 0x02;
        const byte BORDER_BOTTOM = 0x01;
        byte[,] borderState = new byte[rowCount, columnCount];
        int column = columnCount - 1;
        int columnSpan;
        int row = rowCount - 1;
        int rowSpan;
        #region generate main border data
        for (int i = 0; i < rowCount; i++)
        {
            borderState[i, 0] = BORDER_LEFT;
            borderState[i, column] = BORDER_RIGHT;
        }

        for (int i = 0; i < columnCount; i++)
        {
            borderState[0, i] |= BORDER_TOP;
            borderState[row, i] |= BORDER_BOTTOM;
        }
        #endregion

        #region generate child border data
        UIElementCollection children = this.InternalChildren;
        foreach (UIElement child in children)
        {
            this.GetChildLayout(child, out row, out rowSpan, out column, out columnSpan);
            for (int i = 0; i < rowSpan; i++)
            {
                borderState[row + i, column] |= BORDER_LEFT;
                borderState[row + i, column + columnSpan - 1] |= BORDER_RIGHT;
            }
            for (int i = 0; i < columnSpan; i++)
            {
                borderState[row, column + i] |= BORDER_TOP;
                borderState[row + rowSpan - 1, column + i] |= BORDER_BOTTOM;
            }
        }
        #endregion

        #region draw border
        Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
        double left;
        double top;
        double width, height;


        for (int r = 0; r < rowCount; r++)
        {
            RowDefinition v = rows[r];
            top = v.Offset;
            height = v.ActualHeight;
            for (int c = 0; c < columnCount; c++)
            {
                byte state = borderState[r, c];

                ColumnDefinition h = columns[c];
                left = h.Offset;
                width = h.ActualWidth;
                if ((state & BORDER_LEFT) == BORDER_LEFT)
                {
                    dc.DrawLine(pen, new Point(left, top), new Point(left, top + height));
                }
                if ((state & BORDER_TOP) == BORDER_TOP)
                {
                    dc.DrawLine(pen, new Point(left, top), new Point(left + width, top));
                }
                if ((state & BORDER_RIGHT) == BORDER_RIGHT && (c + 1 >= columnCount || (borderState[r, c + 1] & BORDER_LEFT) == 0))
                {
                    dc.DrawLine(pen, new Point(left + width, top), new Point(left + width, top + height));
                }
                if ((state & BORDER_BOTTOM) == BORDER_BOTTOM && (r + 1 >= rowCount || (borderState[r + 1, c] & BORDER_TOP) == 0))
                {
                    dc.DrawLine(pen, new Point(left, top + height), new Point(left + width, top + height));
                }
            }

        }
        #endregion
    }

    private void GetChildBounds(UIElement child, out double left, out double top, out double width, out double height)
    {
        ColumnDefinitionCollection columns = this.ColumnDefinitions;
        RowDefinitionCollection rows = this.RowDefinitions;
        int rowCount = rows.Count;

        int row = (int)child.GetValue(Grid.RowProperty);
        if (row >= rowCount)
        {
            row = rowCount - 1;
        }

        int rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
        if (row + rowSpan > rowCount)
        {
            rowSpan = rowCount - row;
        }
        int columnCount = columns.Count;

        int column = (int)child.GetValue(Grid.ColumnProperty);
        if (column >= columnCount)
        {
            column = columnCount - 1;
        }

        int columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
        if (column + columnSpan > columnCount)
        {
            columnSpan = columnCount - column;
        }

        left = columns[column].Offset;
        top = rows[row].Offset;
        ColumnDefinition right = columns[column + columnSpan - 1];
        width = right.Offset + right.ActualWidth - left;
        RowDefinition bottom = rows[row + rowSpan - 1];
        height = bottom.Offset + bottom.ActualHeight - top;
        if (width < 0D)
        {
            width = 0D;
        }

        if (height < 0D)
        {
            height = 0D;
        }

    }
    private void GetChildLayout(UIElement child, out int row, out int rowSpan, out int column, out int columnSpan)
    {
        int rowCount = this.RowDefinitions.Count;

        row = (int)child.GetValue(Grid.RowProperty);
        if (row >= rowCount)
        {
            row = rowCount - 1;
        }

        rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
        if (row + rowSpan > rowCount)
        {
            rowSpan = rowCount - row;
        }
        int columnCount = this.ColumnDefinitions.Count;

        column = (int)child.GetValue(Grid.ColumnProperty);
        if (column >= columnCount)
        {
            column = columnCount - 1;
        }

        columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
        if (column + columnSpan > columnCount)
        {
            columnSpan = columnCount - column;
        }
    }

    private static void OnBorderBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateVisual();
        }
    }

    private static void OnBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateArrange();
        }
    }

    private static void OnCellSpacingChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateArrange();
        }
    }

    private static object CoerceBorderThickness(DependencyObject d, object baseValue)
    {
        if (baseValue is double value)
        {
            return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
        }

        return 0D;
    }
    private static object CoerceCellSpacing(DependencyObject d, object baseValue)
    {
        if (baseValue is double value)
        {
            return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
        }

        return 0D;
    }
}

데모:

열과 행으로 분리된 그리드를 줄 바꿈하려는 경우 다음과 같이 span 옵션을 사용할 수 있습니다.

<Grid Grid.ColumnSpan="4"  Grid.Row ="1" Grid.RowSpan="3" ShowGridLines="True" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <Border Margin="10" BorderBrush="Gray" BorderThickness="2" Grid.ColumnSpan="2" Grid.RowSpan="4"/>
</Grid>

다음 정보를 제공합니다.

언급URL : https://stackoverflow.com/questions/2769291/how-could-i-put-a-border-on-my-grid-control-in-wpf

반응형