I need the following xaml code snippet in cs (code behind file)
<ToolBarTray Width="450" IsLocked="True" >
<ToolBar Width="{Binding ActualWidth,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ToolBarTray}}}">
<Button>B1</Button>
<Button>B2</Button>
</ToolBar>
</ToolBarTray>
If you really intend to use this code in the codebehind than the snippet below should be fine. However, it will not work if you want to create a DataTemplate from code. In that case you need to use FrameworkElementFactory derived types and not FrameoworkElement derived types.