WPF:如何获取自定义图像ActualWidth值?

编程入门 行业动态 更新时间:2024-10-14 10:41:34
本文介绍了WPF:如何获取自定义图像ActualWidth值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

目标:获取自定义图像的ActualWidth值。 问题:ActualWidth值始终为0. 问题:如何获得正确的自定义图像ActualWidth价值? 代码:

public 部分 类 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 覆盖 void OnRender(DrawingContext dc) { dc.DrawRectangle(Brushes.Red, null , new Rect( 0 , 0 , 100 , 100 )); } }

解决方案

DrawingContext完成的绘图大小(Rectangle)与UIElement的大小不同。 Image类和UIElement类都没有属性可以获得绘图的大小。您可以定义自己的自定义属性,以便能够获得绘制的矩形的高度和宽度:

public class MyImage:Image { protected 覆盖 void OnRender(DrawingContext dc) { dc.DrawRectangle(Brushes.Red, null , new Rect( 0 , 0 , 100 , 100 )); 此 .RectHeight = 100 ; 此 .RectWidth = 100 ; } public double RectHeight {获得; private set ; } public double RectWidth { get ; private set ; } }

资料来源: social.msdn.microsoft/Forums/en-US / 2f512dd6-cf81-46a6-ab38-e9f7cc483030 / wpf-how-to-get-a-custom-image-actualwidth-value [ ^

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:

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)); } }

解决方案

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:

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: social.msdn.microsoft/Forums/en-US/2f512dd6-cf81-46a6-ab38-e9f7cc483030/wpf-how-to-get-a-custom-image-actualwidth-value[^]

更多推荐

WPF:如何获取自定义图像ActualWidth值?

本文发布于:2023-11-15 22:16:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   图像   WPF   ActualWidth

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!