UWP模板10创建一个动态汉堡包

时间:2016-02-05 19:10:52

标签: c# winrt-xaml uwp template10

我对UWP很不错。我正在尝试创建动态汉堡包菜单。 我能够创建PrimaryButtons元素,并在XAML中绑定它按预期工作:

var loginButton = new HamburgerButtonInfo();
loginButton.ClearHistory = true;
loginButton.PageParameter = "";
loginButton.PageType = typeof(Views.Login);
var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
stackPanel.Children.Add(new SymbolIcon { Symbol = Symbol.Contact, Width = 48, Height = 48 });
stackPanel.Children.Add(new TextBlock { Text = "Login", VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(12, 0, 0, 0) });
loginButton.Content = stackPanel;

但是我希望有一个更清洁的解决方案,所以我尝试扩展HamburgerButtonInfo类:

class MenuItem : HamburgerButtonInfo
{
    private Symbol symbol;
    private String text;
    StackPanel stackpanel = new StackPanel { Orientation = Orientation.Horizontal };
    TextBox textbox = new TextBox { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(12, 0, 0, 0) };
    SymbolIcon symbolicon = new SymbolIcon { Width = 48, Height = 48 };

    public MenuItem():base()
    {
        StackPanel.Children.Add(symbolicon);
        StackPanel.Children.Add(textbox);
        this.Content = StackPanel;
    }

    public String Text
    {
        get { return text; }
        set {
            textbox.Text = value;
            Set(ref text, value);
        }
    }

    public StackPanel StackPanel
    {
        get { return stackpanel; }
    }

    public Symbol Symbol
    {
        get { return symbol; }
        set {
            symbolicon.Symbol = value;
            Set(ref symbol, value);
        }
    }
}

总而言之,我希望得到相同的结果:

PrimaryButtons.Add(loginButton);
PrimaryButtons.Add(new MenuItem() { PageType=typeof(Views.Login), PageParameter="", ClearHistory=true, Text="Login", Symbol=Symbol.Contact });

但这是结果

enter image description here

我错过了什么吗?对于这种情况,这是正确的方法吗?

1 个答案:

答案 0 :(得分:4)

可以吗?绝对

var stackPanel = new StackPanel
{
    Orientation = Orientation.Horizontal
};
stackPanel.Children.Add(new SymbolIcon
{
    Width = 48,
    Height = 48,
    Symbol = Symbol.UnSyncFolder
});
stackPanel.Children.Add(new TextBlock
{
    Margin = new Thickness(12, 0, 0, 0),
    VerticalAlignment = VerticalAlignment.Center,
    Text = "UnSync Folder"
});
var button = new HamburgerButtonInfo
{
    Content = stackPanel,
    ButtonType = HamburgerButtonInfo.ButtonTypes.Toggle,
    ClearHistory = false,
    PageType = typeof(Views.DetailPage)
};
MyHamburgerMenu.PrimaryButtons.Add(button);

看起来像这样(我在搜索示例中尝试过)。

enter image description here

它更冗长,因为XAML语法非常紧凑,但如果您愿意,可以在代码隐藏中执行此操作。如果可以选择,您可能只想更改现有按钮的可见性。

祝你好运!