Jonathan Allen Jonathan Allen - 6 months ago 39
Vb.net Question

WPF: Databinding to parameterized properties

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

Answer

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.