Wpf 在工具栏托盘中拉伸工具栏代码隐藏和xaml

Wpf 在工具栏托盘中拉伸工具栏代码隐藏和xaml,wpf,xaml,binding,code-behind,Wpf,Xaml,Binding,Code Behind,我需要cs(代码隐藏文件)中的以下xaml代码片段 地下一层 地下二层 如果您真的打算在codebehind中使用此代码,那么下面的代码片段应该可以。但是,如果您想从代码创建DataTemplate,它将不起作用。在这种情况下,您需要使用FrameworkElement工厂派生类型,而不是FrameworkElement派生类型 public ToolBarTray CreatetoolBarTray() { var tbt = new ToolBarTray

我需要cs(代码隐藏文件)中的以下xaml代码片段


地下一层
地下二层

如果您真的打算在codebehind中使用此代码,那么下面的代码片段应该可以。但是,如果您想从代码创建DataTemplate,它将不起作用。在这种情况下,您需要使用FrameworkElement工厂派生类型,而不是FrameworkElement派生类型

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;
    }
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;
    }