Laden...

WPF - Programmatically added button with template not displayed

Erstellt von thooobi vor 6 Jahren Letzter Beitrag vor 6 Jahren 1.698 Views
T
thooobi Themenstarter:in
26 Beiträge seit 2011
vor 6 Jahren
WPF - Programmatically added button with template not displayed

Hi,

i am trying to add a button with an image programmatically.

My code:

var bitmap = new BitmapImage(new Uri("/Resources/Images/minus.png", UriKind.RelativeOrAbsolute));

            var template = new ControlTemplate(typeof(Button));
            var image = new FrameworkElementFactory(typeof(Image));
            image.SetValue(Image.SourceProperty, bitmap);
            image.SetValue(Image.WidthProperty, 20.0);
            image.SetValue(Image.HeightProperty, 20.0);
            template.VisualTree = image;

            

            var minusButton = new Button()
            {
                Template = template
            };
            

            row.Children.Add(minusButton);

Tried a lot of variations and ideas from stackoverflow and other communities, but nothing is working for me. Unfortunatelly the button doesnt shows up.

Is the way i am trying the correct one?

Thanks
Thobi

M
177 Beiträge seit 2009
vor 6 Jahren

Wird der Button überhaupt im Visual Tree angezeigt? Also im Sinne wird er im Visual Tree aufgelistet. Was sagt der WPF Inspector?

T
thooobi Themenstarter:in
26 Beiträge seit 2011
vor 6 Jahren

Solution: BitmapImage Uri was not correct

var bitmap = new BitmapImage(new Uri("pack://application:,,,/Finanzer;component/Resources/Images/minus.png", UriKind.RelativeOrAbsolute));