2012-03-09 14 views
0

我需要在CS下面的XAML代碼片段(隱藏文件的代碼)Streching工具欄在toolbartray代碼隱藏和XAML

<ToolBarTray Width="450" IsLocked="True" > 
<ToolBar Width="{Binding ActualWidth,  
RelativeSource={RelativeSource FindAncestor,  
AncestorType={x:Type ToolBarTray}}}"> 
<Button>B1</Button> 
<Button>B2</Button> 
</ToolBar> 
</ToolBarTray> 

回答

0

如果你真的打算在代碼隱藏比片段使用此代碼下面應該是罰款。但是,如果你想從代碼創建一個DataTemplate,它將不起作用。在這種情況下,您需要使用FrameworkElementFactory派生類型,而不是FrameoworkElement派生類型。

public ToolBarTray CreatetoolBarTray() 
    { 
     var tbt = new ToolBarTray 
         { 
          Width = 450.0, 
          IsLocked = true 
         }; 
     var tb = new ToolBar(); 
     var b = new Binding 
        { 
         Path = new PropertyPath("ActualWidth"), 
         Source = new RelativeSource(RelativeSourceMode.FindAncestor, typeof (ToolBarTray), 1), 
        }; 
     tb.SetBinding(WidthProperty, b); 

     tb.Items.Add(new Button() {Content = "b1"}); 
     tb.Items.Add(new Button() {Content = "b2"}); 

     tbt.ToolBars.Add(tb); 

     return tbt; 
    }