如何为XAML网格代码创建C#代码?

时间:2018-09-16 10:45:24

标签: c# wpf xaml grid

嗨,我如何为该xaml代码创建c#代码?

 <Grid Width="300" Height="330">
        <Grid.Effect>
            <DropShadowEffect
                BlurRadius="15"
                Direction="-90"
                Opacity=".2"
                RenderingBias="Quality"
                ShadowDepth="1" />
        </Grid.Effect>
        <Grid.OpacityMask>
            <VisualBrush Visual="{Binding ElementName=Border2}" />
        </Grid.OpacityMask>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height=".50*" />
            <RowDefinition Height=".5*" />
        </Grid.RowDefinitions>
        <Border
            x:Name="Border2"
            Grid.Row="0"
            Grid.RowSpan="4"
            Background="White"
            CornerRadius="5" />
        <Border
            Grid.Row="0"
            Grid.RowSpan="3"
            Background="{Binding BorderColor}" />
       <StackPanel
            Grid.Row="3"
            Margin="20,0,20,0"
            VerticalAlignment="Center">

            <StackPanel Orientation="Horizontal">

            </StackPanel>
        </StackPanel>
    </Grid>

我需要创建许多控件,因此我必须从C#代码创建ui。请告诉我我该怎么做?我的问题是我无法在c#中创建Grid.Effect。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式用C#代码动态创建Grid

Grid grid = new Grid()
{
    Width = 300,
    Height = 300
};
grid.Effect = new DropShadowEffect()
{
    BlurRadius = 15,
    Direction = -90,
    Opacity = .2,
    RenderingBias = RenderingBias.Quality,
    ShadowDepth = 1
};
grid.RowDefinitions.Add(new RowDefinition());
grid.RowDefinitions.Add(new RowDefinition());
// ... add more rows
// Create children:
var border = new Border()
{
    Background = new SolidColorBrush(Colors.White),
    CornerRadius = new CornerRadius(5)
};
Grid.SetRow(border, 0);
Grid.SetRowSpan(border, 4);
grid.Children.Add(border);
// ... add more children

我开始在此处转换您的XAML代码的一部分以显示该原理。有关更多示例,您还可以参考this article