本文介绍了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值?
发布评论