views:

27

answers:

1

I have a custom converter that has a DefaultText property. All my converter does is return the DefaultText if the string is null or empty. I can't seem to get it to work though. Here's what I've got. This is the converter class.

public class DisplayValueConverter : DependencyObject, IValueConverter
{
    public static readonly DependencyProperty DefaultTextProperty = DependencyProperty.Register( "DefaultText",
                                                                                                 typeof ( string ),
                                                                                                 typeof ( DisplayValueConverter ) );

    public string DefaultText
    {
        get { return ( string ) GetValue( DefaultTextProperty ); }
        set { SetValue( DefaultTextProperty, value ); }
    }

    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {

        string empty = ( parameter != null ) ? parameter as string : DefaultText;
        return ( value != null && !string.IsNullOrEmpty( value.ToString().Trim() ) ) ? value.ToString() : empty;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
        return null;
    }
}

And this is my xaml putting it into use.

        <TextBox Grid.Column="1"
                 Grid.Row="3"
                 VerticalAlignment="Center"
                 Margin="0,0,10,0" >
            <TextBox.Text>
                <Binding Path="DataSource.Payee"
                         Mode="TwoWay"
                         NotifyOnSourceUpdated="True"
                         NotifyOnTargetUpdated="True"
                         NotifyOnValidationError="True"
                         ValidatesOnDataErrors="True"
                         UpdateSourceTrigger="PropertyChanged">
                    <Binding.Converter>
                        <k:DisplayValueConverter DefaultText="{Binding ElementName=This, Path=Test, Mode=TwoWay}" />
                    </Binding.Converter>
                    <Binding.ValidationRules>
                        <vr:RequiredField Label="Payee" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

I've verified that the DataContext has an object, and that the Path works. So I'm not sure what I'm doing wrong.

+1  A: 

I think the problem is with your use of Binding.ElementName. Because your value converter isn't actually part of the visual or logical tree, the binding engine has no way of knowing what tree it needs to traverse in order to find the element with the matching ElementName.

In this scenario, your best bet is going to be to specifically set the binding's Source property from code behind, or maybe creating a custom markup extension that would grab the right object for you.

rossisdead
This makes sense. I set the binding in code at it works like a charm.
Matt