在toolbartray codebehind和xaml中拉伸工具栏

问题描述 投票:0回答:1

我需要cs中的以下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>
wpf xaml binding code-behind
1个回答
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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.