在代码中设置边距属性 [英] Setting Margin Properties in code

查看:247
本文介绍了在代码中设置边距属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  MyControl.Margin.Left = 10; 



错误:




无法修改的'System.Windows.FrameworkElement.Margin'的返回值,因为它不是一个变量



解决方案

的问题是, 保证金 是一个属性,它的类型( 厚度 )是值类型。当你访问你得到的复制的值回的财产的手段。



即使你的可以改变 Thickness.Left 属性特定值(GRR ...可变的值类型应该不存在),也不会改变保证金。



相反,你需要在保证金属性设置为一个新值。例如(巧合的是马克写了相同的代码):

 厚度保证金= MyControl.Margin; 
margin.Left = 10;
MyControl.Margin =保证金;



对于库设计一张纸条,我会大大如果厚度更喜欢它是一成不变的,而是与返回一个新的值是原件及复印件,但有一个部分替代方法。然后,你可以写:

  MyControl.Margin = MyControl.Margin.WithLeft(10); 

没有担心可变的值类型,好看可读的古怪行为,都是一个表情...


MyControl.Margin.Left = 10;

Error:

Cannot modify the return value of 'System.Windows.FrameworkElement.Margin' because it is not a variable

解决方案

The problem is that Margin is a property, and its type (Thickness) is a value type. That means when you access the property you're getting a copy of the value back.

Even though you can change the value of the Thickness.Left property for a particular value (grr... mutable value types shouldn't exist), it wouldn't change the margin.

Instead, you'll need to set the Margin property to a new value. For instance (coincidentally the same code as Marc wrote):

Thickness margin = MyControl.Margin;
margin.Left = 10;
MyControl.Margin = margin;

As a note for library design, I would have vastly preferred it if Thickness were immutable, but with methods that returned a new value which was a copy of the original, but with one part replaced. Then you could write:

MyControl.Margin = MyControl.Margin.WithLeft(10);

No worrying about odd behaviour of mutable value types, nice and readable, all one expression...

这篇关于在代码中设置边距属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆