Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to attributes

I have a class

public class Car 
{
    [Description("name of the car")]
    public string Name { get; set; }

    [Description("age of the car")]
    public int Age { get; set; }
}

Is there any possibility to bind Description attribute to Label content. The solution what I'm looking for shouldn't require to instantiate Car object.

like image 312
torpederos Avatar asked Sep 19 '12 10:09

torpederos


People also ask

How do you bind a value in style attribute?

Binding to a single stylelink To create a single style binding, use the prefix style followed by a dot and the name of the CSS style. Angular sets the property to the value of the bound expression, which is usually a string. Optionally, you can add a unit extension like em or % , which requires a number type.

What is property binding with example?

In Angular 7, property binding is used to pass data from the component class (component. ts) and setting the value of the given element in the user-end (component. html). Property binding is an example of one-way databinding where the data is transferred from the component to the class.

What are the types of data binding?

As mentioned earlier, one-way data binding in Angular can be of three types i.e Interpolation, Property binding, and Event binding.

What is data binding which are 2 types of data binding?

One-way binding is a relatively simple type of data binding. Changes to the data provider update automatically in the data consumer data set, but not the other way around. Two-way binding is where changes to either the data provider or the data consumer automatically updates the other.


2 Answers

instead of string literal use string constant to set attribute parameter:

public class Car
{
    public const string CarNamePropertyDescription = "name of the car";
    
    [Description(CarNamePropertyDescription)]
    public string Name { get; set; }
}

constants can be accessed from xaml via {x:Static} extension (no need for Binding since attribute isn't going to change in runtime):

<Label Content="{x:Static namespace:Car.CarNamePropertyDescription}"/>
like image 173
ASh Avatar answered Oct 05 '22 14:10

ASh


It won't be a proper binding (which is not necessary for static data anyway) but you can easily create a MarkupExtension to retrieve it, just pass the type and the property name and get it via reflection.

Outline would be something like:

public Type Type { get; set; }
public string PropertyName { get; set; }

ProvideValue: Type.GetProperty(PropertyName)
                  .GetCustomAttributes(true)
                  .OfType<DescriptionAttribute>()
                  .First()
                  .Description
<!-- Usage example -->
Text="{me:Description Type=local:Car, PropertyName=Name}"
like image 40
H.B. Avatar answered Oct 05 '22 14:10

H.B.