如何以编程方式创建ThemeShadow? (C#UWP 1903)

时间:2019-10-04 11:29:57

标签: c# xaml uwp

我尝试以编程方式创建ThemeShadow,但是无法解决Resources中的XAML部分。我这样称呼voidCreateTheme(Test,SharedShadow);。我喜欢摆脱调用SharedShadow参数上的void部分,而不使它在没有XAML中的代码的情况下也可以工作。怎么做?

XAML

<Grid>
    <!--HOW TO MAKE THIS PART (RESOURCES) PROGRAMMATICALLY?-->
    <Grid.Resources>
        <ThemeShadow x:Name="SharedShadow" />
    </Grid.Resources>
    <Rectangle x:Name="Test" Width="200" Height="70" Fill="DarkGray" Shadow="{StaticResource SharedShadow}"></Rectangle>
</Grid>

无效-C#

public static void CreateTheme(FrameworkElement TargetFrameworkElement, ThemeShadow SharedShadow)
{
    //In this case we know the Parent will be Grid...
    Grid TargetGrid = VisualTreeHelper.GetParent(TargetFrameworkElement) as Grid;
    //Create the Grid for Shadow        
    Grid ShadowGrid = new Grid() {Margin=new Thickness(-16) };
    //Insert it as first element in its Parent
    TargetGrid.Children.Insert(0, ShadowGrid);
    //Recievers
    SharedShadow.Receivers.Add(ShadowGrid);
    //Translation
    TargetFrameworkElement.Translation += new Vector3(0, 0, 16);
}

1 个答案:

答案 0 :(得分:0)

终于解决了。以下代码效果很好。只需这样调用voidCreateTheme(Test, 16); TestRectangle的名称,16是阴影的Depth

XAML

<Grid>
    <Rectangle x:Name="Test" Width="200" Height="70" Fill="DarkGray"></Rectangle>
</Grid>

C#

    public static void CreateTheme(FrameworkElement TargetFrameworkElement, int ZDepth)
    {
        //MAKE SURE THAT PARENT IS TYPE OF GRID
        if (VisualTreeHelper.GetParent(TargetFrameworkElement) is Grid)
        {
            //GET PARENT GRID
            Grid ParentGrid = VisualTreeHelper.GetParent(TargetFrameworkElement) as Grid;
            //CREATE BORDER FOR SHADOW (RECIEVER). MAKE SURE THERE ARE SPACE TO SHOW SHADOW SO SET MARGIN NEGATIVE.
            Border ShadowReciever = new Border() { Margin = new Thickness(-ZDepth) };
            //ADD RECIEVER TO PARENT GRID
            ParentGrid.Children.Insert(0, ShadowReciever);
            //CREATE NEW THEME SHADOW
            ThemeShadow SharedShadow = new ThemeShadow();
            //CONNECT SHADOW TO FRAMEWORK ELEMENT
            TargetFrameworkElement.Shadow = SharedShadow;
            //CONNECT RECIEVER TO THEME SHADOW
            SharedShadow.Receivers.Add(ShadowReciever);
            //SET SHADOW DEPTH
            TargetFrameworkElement.Translation += new Vector3(0, 0, ZDepth);
        }
        else
        {
            //ERROR. PARENT MUST BE TYPE OF GRID
        }
    }