Assign Mahapps.Metro:IconPacks to button in code behind

匆匆过客 提交于 2019-12-11 04:57:00

问题


I am trying to assign an icon from any Mahapps.Metro.IconPacks to an rectangle respectively to a button with text.

How do I do this if I want to use the new IconPacks?

Effectively I need to convert an Mahapps.Metro.IconPacks.PackIconModernKind to VisualBrush or canvas or actually anything I can use to place it in a button.

Any help is appreciated!

Thanks


回答1:


You can place any IconPack Control directly to the content of the Button or to a container like a Grid.

The Xaml way

<Button Content="Test">
    <Button.ContentTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <iconPacks:PackIconMaterial Kind="Cookie"
                                            Margin="4 4 2 4"
                                            Width="24"
                                            Height="24"
                                            VerticalAlignment="Center" />
                <TextBlock Text="{Binding}"
                            Margin="2 4 4 4"
                            VerticalAlignment="Center" />
            </StackPanel>
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

or

<Button>
    <StackPanel Orientation="Horizontal">
        <iconPacks:PackIconMaterial Kind="Cookie"
                                    Margin="4 4 2 4"
                                    Width="24"
                                    Height="24"
                                    VerticalAlignment="Center" />
        <TextBlock Text="Test"
                    Margin="2 4 4 4"
                    VerticalAlignment="Center" />
    </StackPanel>
</Button>

The code behind way of Xaml version 2

var stackPanel = new StackPanel() { Orientation = Orientation.Horizontal };
var packIconMaterial = new PackIconMaterial()
{
    Kind = PackIconMaterialKind.Cookie,
    Margin = new Thickness(4, 4, 2, 4),
    Width = 24,
    Height = 24,
    VerticalAlignment = VerticalAlignment.Center
};
stackPanel.Children.Add(packIconMaterial);
var textBlock = new TextBlock()
{
    Text = "Test",
    Margin = new Thickness(2, 4, 4, 4),
    VerticalAlignment = VerticalAlignment.Center
};
stackPanel.Children.Add(textBlock);
this.TestButton.Content = stackPanel;

Hope this helps.



来源:https://stackoverflow.com/questions/41117096/assign-mahapps-metroiconpacks-to-button-in-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!