Question

I have been writing lots of data entry type forms in my application and I have come to the conclusion that I need to make it a bit easier. After doing some reading up it seems this can be done using a subclassed ItemsControl to represent the form.

I have done this and now have something like

<MySubClassedForm></MySubClassedForm>

what I would like to do now is set an attached property say "LabelText" so that it can be used on any control inside .

As an example,

<MySubClassedForm>
<TextBox MySubClassedForm.LabelText="Surname" />
<Image MySubClassedForm.LabelText="LabelText" />
</MySubClassedForm>

Attached property definition:-

 public static DependencyProperty LabelTextProperty = DependencyProperty.RegisterAttached("LabelText", typeof(string), typeof(MySubclassedForm),
         new UIPropertyMetadata(string.Empty));

        public string LabelText
        {
            get { return (string)GetValue(LabelTextProperty); }
            set { SetValue(LabelTextProperty, value); }
        }

I started by putting the attached property on MySubClassedForm and I get the following error:-
The attached property 'MySubClassedForm.LabelText' is not defined on 'TextBox' or one of its base classes.

Please can you advise what I am doing wrong and what I need to do to make this work?

Thanks Alex

Was it helpful?

Solution

You would need to define static getter and setter methods:

public static readonly DependencyProperty LabelTextProperty =
    DependencyProperty.RegisterAttached(
        "LabelText", typeof(string), typeof(MySubclassedForm),
        new UIPropertyMetadata(string.Empty)); 

public static string GetLabelText(DependencyObject obj) 
{ 
    return (string)obj.GetValue(LabelTextProperty);
}

public static void SetLabelText(DependencyObject obj, string value) 
{ 
    obj.SetValue(LabelTextProperty, value); 
} 

Get more information here on Custom Attached Properties.

OTHER TIPS

You should take a look at magellan It has both a WPF forms engine and an excellent MVC framework. Either can be used without the other.

It lets you do

<Form>
    <Field For="{Binding Path=Server.Server}" />
    <Field For="{Binding Path=Server.CachedExchangeMode}" />
    <Field For="{Binding Path=Server.Username}" />
    <Field For="{Binding Path=Server.SecurityMode}" />
</Form>

which will auto-generate the proper input field types for the properties on your viewmodel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top