views:

200

answers:

3

Given this class/property, how would I write a WPF data binding expression to get myToken.DataItem("Phone")?

Class Token
    Public Property DataItem(ByVal name As String) As Object
        Get
            If m_DataPoints.ContainsKey(name) Then Return m_DataPoints(name) Else Return Nothing
        End Get
        Set(ByVal value As Object)
            Dim oldValue = DataItem(name)
            If Object.Equals(oldValue, value) Then Return
            m_DataPoints(name) = value
            OnPropertyChanged("DataPoint")
        End Set
    End Property
End Class
A: 

A binding cannot have a parameter.

I suggest writing a converter. A converter can have a parameter, which it can use to access the indexed property.

Another thing to try is to write an implementation of ICustomTypeDescriptor, where you return a subclass of PropertyDescriptor for each of the keys in the DataItem. This subclass will use DataItem to implement GetValue.

WPF will believe that you have a Phone property and will go through the PropertyDescriptor to get its value. The binding becomes simply: {Binding Path=Phone}.

Timores
A: 

Why don't you provide a property "Phone"?

winSharp93
Token is a generic object that holds basic information like CustomerKey, FirstName, and LastName. I'm looking for a place to shove additional information that comes back from queries without have to create countless subclasses.
Jonathan Allen
See my new proposition.
Timores
+2  A: 

Binding's indexer syntax should work for you as long as your indexed property is declared as default:

Default Public Property DataItem(ByVal name As String) As Object 

In this case you can use:

<TextBox Text="{Binding Token[Phone]}" />

or if your token is your DataContext just:

<TextBox Text="{Binding [Phone]}" />

WPF's Binding syntax has no mechanism for accessing a non-default indexer. If you cannot make your indexer default, you'll have to use a converter:

<TextBox Text="{Binding Token,ConverterParameter=Phone,Converter={x:Static my:DataItemAccessor.Instance}}" />

Where DataItemAccessor is a trivial class you write that implements IValueConverter and accessed DataItem.

Ray Burns
"WPF's Binding syntax has no mechanism for accessing a non-default indexer." Again they treat VB as a second-class langauge. Oh well, I'm still early enough in the process that I can use a default indexer instead.
Jonathan Allen