Reputation: 3459
On the top it says, "Gets or sets...", so then why is it not letting me change it?
Upvotes: 3
Views: 1723
Reputation: 65054
The point here is that it makes no sense to assign to a property within a temporary struct
value, as it has no lasting effect.
System.Windows.Thickness is a struct
, and label1.Margin
is a copy of the Thickness
value for the margin of label1
. It's a copy because struct
s are passed by value. There's no point assigning to label1.Margin.Left
as you will only change the value of Left
in a copy of label1.Margin
.
What you can do instead is the following:
Thickness t = label1.Margin;
t.Left = ......; // assign your value here
label1.Margin = t;
See also the MSDN page for the CS1612 error.
The tooltip is saying 'Gets or sets...' because you can get or set the Margin
property of label1
, but in your specific case there's no point assigning to the Left
property of label1.Margin
.
Upvotes: 0
Reputation: 5571
You can't do this because although Margin.Left
gets or sets, it's not used like a variable. Just like Padding
.
As you may notice, Margin
(as for Padding
) is a property and Thickness
is its value. So, when you say
label1.Margin.Left = MainGrid.ActualHeight / 2 - label1.ActualHeight / 2;
you are only editing a copy (Margin
) because Margin
returns a struct (Thickness
) . That's why you receive an error. The changes are not saved because it's a copy!
Basically, although you can change the value of Object.Margin.Left
to a specific value yet it wouldn't save/change the object Margin
property and that's why you get an error.
We can NOT say
label1.Margin.Left = MainGrid.ActualHeight / 2 - label1.ActualHeight /2;
but we can say
Thickness NewThickness = new Thickness(); //Initialize a new Thicnkess
NewThickness.Left = MainGrid.ActualHeight / 2 - label1.ActualHeight /2; //Set the left property of NewThickness
label1.Margin = NewThickness; //Apply the changes to label1
This means that, because Margin
is a property, you are not allowed to change its Thickness
directly.
Alternatively, you can use the following which I believe to be easier to set a Margin
of an object
label1.Margin = new Thickness(double left, double top, double right, double bottom);
Thanks,
I hope you find this helpful :)
Upvotes: 4
Reputation: 14361
Seems like all arguments are mandatory for the WPF Margin property, although you may want change just one or two property values a time...
with Google search I saw in Java as well as ASP.net using margin property with all 4 values set.
However this example allows user to retrieve Label.Margin.Left value though... http://forums.asp.net/t/1834713.aspx/1
Upvotes: 0