我尝试以编程方式创建ThemeShadow
,但是无法解决Resources
中的XAML
部分。我这样称呼void
:CreateTheme(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);
}
答案 0 :(得分:0)
终于解决了。以下代码效果很好。只需这样调用void
:CreateTheme(Test, 16);
Test
是Rectangle
的名称,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
}
}