How to bind the attributes of model properties to a view?
I have a model, for example:
class MyModel
{
[Display(
ResourceType = typeof(Resources.Strings),
Name = "MyName",
Description = "MyDescription")]
public double MyProperty { get; set; }
}
And my view model is something like this (none unusual):
public class MyVM
{
private Models.MyModel model;
public string MyVMProperty
{
get { return model.MyProperty.ToString(); }
set
{
// some usual code with parsing a value from textbox...
}
}
}
And in a view I want to bind the data from the attributes of model properties. Something like this:
<Grid Name="myGrid">
<TextBox
Text="{Binding Path=MyVMProperty}"
/>
<TextBlock
Text="{Binding Path=MyVM.model.MyProperty.DisplayAttribute.Name}"
/>
<TextBlock
Text="{Binding Path=MyVM.model.MyProperty.DisplayAttribute.Description}"
/>
</Grid>
And somewhere in code I do:
myGrid.DataContext = new MyVM();
How to get it?
One of the possible solution is to add helper class and pass the instance of that class as converter parameter. The instance must be initialized in XAML by hands. The instance consist of all the data required to obtain the value of the attribute of the property of the model instance. The solution is generalized and there are no hardcoded data inside of the converter logic. The “value” parameter of the converter is not required also.
So, the result looks like this:
Something in the same assembly as view model. Converter and helper class (simplified – without any null checks etc.):
In resource file (XAML):
In view file: