Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Goal: To get an ActualWidth value of a custom image.
Problem: The ActualWidth value is always 0.
Question: How to get a right custom image ActualWidth value?
Code:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        MyImage myimage = new MyImage();
        MessageBox.Show(myimage.ActualWidth.ToString()); // 0
    }
}

class MyImage : Image
{
    protected override void OnRender(DrawingContext dc)
    {
        dc.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
    }
}
Posted

1 solution

The size of the drawing (Rectangle) done by the DrawingContext is not the same thing as the size of the UIElement. There are no properties of the Image class nor the UIElement class that gets you the size of the drawing. You could define your own custom properties to be able to get the Height and Width of the drawn Rectangle:
C#
public class MyImage : Image
    {
        protected override void OnRender(DrawingContext dc)
        {
            dc.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
            this.RectHeight = 100;
            this.RectWidth = 100;
        }

        public double RectHeight { get; private set; }
        public double RectWidth { get; private set; }
    }

Source:
https://social.msdn.microsoft.com/Forums/en-US/2f512dd6-cf81-46a6-ab38-e9f7cc483030/wpf-how-to-get-a-custom-image-actualwidth-value[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900