开发者

How do I set XAML Elements from C# code?

So i have wpf application and my xaml looks like this:

<Window x:Class="MyTest"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:MyTest.Layouts"
        xmlns:pl="clr-namespace:Planerator"
        Title="CardView" Topmost="False" AllowsTransparency="True" WindowStyle="None" WindowState="Maximized"开发者_StackOverflow ShowInTaskbar="False">
    <Grid>
        <pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
            <my:FrontLayout />
        </pl:Planerator>

        <pl:Planerator x:FieldModifier="public" x:Name="BackProjection" Margin="240" >
            <my:BackLayout />
        </pl:Planerator>
    </Grid>
    <Window.Background>
        <SolidColorBrush />
    </Window.Background>
</Window>

Is there a way to set the <my:FrontLayout /> and <my:FrontLayout /> for the Planerators inside my C# code?

EDIT: Planerator: http://blogs.msdn.com/b/greg_schechter/archive/2007/10/26/enter-the-planerator-dead-simple-3d-in-wpf-with-a-stupid-name.aspx

And the FrontLayot and BackLayout -s are just simple xaml layouts.

EDIT2: The reason why i need to set them from code is that i want o use conditional compilasion. because for example for DEBUG it should be <my:DebugFrontLayer /> .


Looking at the Planerator class you'll see it has the ContentPropertyAttribute set:

[ContentProperty("Child")]
public class Planerator : FrameworkElement
{
}

This means that

  <pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
    <my:FrontLayout />
  </pl:Planerator> 

Actually does this:

  <pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
    <pl:Planerator.Child>
      <my:FrontLayout />
    </pl:Planerator.Child>
  </pl:Planerator>

Which also means that from code-behind, for example in the constructor of MyTest, or anywhere else really, you could do the following to achieve the same:

    public MyTest()
    {
        InitializeComponent();            
        FrontProjection.Child = new FrontLayout();
    }


Give them names, e.g.

<my:FrontLayout Name="FrontLayout1" />

and then they should be accessible from C# as variables of that name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜