views:

416

answers:

1

I have a custom user control named Field:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" Name="LblName"/>
    <TextBox Grid.Row="0" Grid.Column="1" HorizontalContentAlignment="Left" Name="TxtValue"/>
</Grid>

In the CS file I expose the below property that simply sets the ".text" value of the textbox.

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value",
        typeof(string),
        typeof(Field),
        new PropertyMetadata(
            default(string),
            (source, args) => (source as Field).TxtValue.Text = (string)args.NewValue
        )
    );

    [Category("Custom")]
    public string Value
    {
        get
        {
            return (string)this.GetValue(ValueProperty);
        }
        set
        {
            this.SetValue(ValueProperty, value);
        }
    }

First question. Is this the correct way in which we propagate child user control dependancy properties, backup through the parent user control so that it can be set from the page xaml? I've had a look around on the net, there isn't much there considering that this is a fairly primitive thing todo when writing custom controls.

Giving details around the bigger picture, I have customer details page, some the controls are bound to the customer object which is contained in an observable collection. If I change the value of the text box (which is contained within the Field control) on the page from "xxxx" to "yyyy" I always get back "xxxx". It seems like something is going wrong somewhere around the getter?

A: 

This is definitely a step in the right direction for allowing properties to propagate.

If this is a true custom control (derives from Control), you'd want to use a {TemplateBinding Value} plus you should probably also connect to the TextChanged event on the TextBox, after setting up the template part in the OnApplyTemplate method. That way, you can have it also update your underlying TxtValue dependency property as well.

If this is a UserControl, you may be able to use Binding, but you do have a few less options to go to. As you have it, your property changed callback function is only going in one direction: you only set the Text value, you never react to it.

Let's hope the documentation out there improves.

Jeff Wilcox