Jonathan Allen Jonathan Allen - 1 year ago 133 Question

WPF: Databinding to parameterized properties

Given this class/property, how would I write a WPF data binding expression to get


Class Token
Public Property DataItem(ByVal name As String) As Object
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
End Set
End Property
End Class

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download