wpf 如何以编程方式为网格的单元格创建边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26970269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:42:18  来源:igfitidea点击:

How to programmatically create border for cells of a Grid

c#wpfxaml

提问by user2192101

<Grid x:Name="LayoutGrid" Visibility="Visible" Background="Transparent" Canvas.Left="20">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="200"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="600" />
                </Grid.RowDefinitions>
                <Border Grid.Row="0" Grid.Column="0"  BorderBrush="Black"  BorderThickness="1" />
                <Border Grid.Row="2" Grid.Column="0"  BorderBrush="Black"  BorderThickness="1" />
</Grid>

In this XAML code I am putting a border in two cells of a grid. I need to change the design and do the same thing in C# instead. I know how to instantiate a Border in C# and assign it properties, but how do I associate each Border object with the correct cell in the Grid? (named here 'LayoutGrid' ). In other words how do I do in C# what the element is doing in the XAML code above?

在此 XAML 代码中,我在网格的两个单元格中放置了一个边框。我需要更改设计并在 C# 中做同样的事情。我知道如何在 C# 中实例化一个 Border 并为其分配属性,但是如何将每个 Border 对象与网格中的正确单元格相关联?(此处命名为 'LayoutGrid' )。换句话说,我如何在 C# 中执行元素在上面的 XAML 代码中执行的操作?

回答by dkozl

Assuming that myBorderis already child of LayoutGrid

假设myBorder已经是LayoutGrid

var myBorder = new Border();
LayoutGrid.Children.Add(myBorder)

you either use Gridstatic methods

你要么使用Grid静态方法

Grid.SetColumn(myBorder, 0);
Grid.SetRow(myBorder, 1);

or set DependencyPropertyit directly

或者DependencyProperty直接设置

myBorder.SetValue(Grid.ColumnProperty, 0);
myBorder.SetValue(Grid.RowProperty, 1);

回答by J Armbruster

You need to add a Brush:

您需要添加一个画笔:

Border brdr = new Border() 
{ 
    BorderThickness = new Thickness() 
    { 
        Bottom = 1, 
        Left = 1, 
        Right = 1, 
        Top = 1 
    }, 
    BorderBrush = new SolidColorBrush(Colors.Black) 
};

Then the code listed above will work.

然后上面列出的代码将起作用。