I'm writing my very first Silverlight app. I have a datagrid with a column that has two labels, for the labels, i am using an IValueConverter to conditionally format the data.
The label's "Content" is set as such:
Content="{Binding HomeScore, Converter={StaticResource fmtshs}}"
and
Content="{Binding AwayScore, Converter={StaticResource fmtshs}}"
The Convert method of my IValueConverter is such:
Public Function Convert(
ByVal value As Object,
ByVal targetType As System.Type,
ByVal parameter As Object,
ByVal culture As System.Globalization.CultureInfo) As Object
Implements System.Windows.Data.IValueConverter.Convert
Dim score As Long = value, other As Long = parameter
Return If(score < 0, "",
If(score - other > 5, (other + 5).ToString, score.ToString)
)
End Function
So what i want to do is in the converter for HomeScore, i want to pass AwayScore to the ConverterParameter, and for AwayScore i want to pass the HomeScore to the converter. In the converter for either score i need to be able to know the value of the other score for formatting purposes.
But i cannot figure out the syntax for binding the ConverterParameter to another field.
I've tried the following:
Content="{Binding HomeScore, Converter={StaticResource fmtshs}, ConverterParameter=AwayScore}"
Content="{Binding HomeScore, Converter={StaticResource fmtshs}, ConverterParameter={AwayScore}}"
Content="{Binding HomeScore, Converter={StaticResource fmtshs}, ConverterParameter={Binding AwayScore}}"
But none of those seem to work. How do i pass a field value to the ConverterParameter?
As you can't pass anything but a literal into the ConverterParameter
the solution is to pass the whole object into the converter and then you can access all of it's properties from within the Converter.
So your code becomes (assuming your object is called Match
):
Public Function Convert(
ByVal value As Object,
ByVal targetType As System.Type,
ByVal parameter As Object,
ByVal culture As System.Globalization.CultureInfo) As Object
Implements System.Windows.Data.IValueConverter.Convert
Dim match As Match = value
' Do stuff with match'
End Function
(Apologies for lack of detail in the code)
Then your XAML becomes
Content="{Binding Converter={StaticResource fmtshs}}"
NOTE While you are apparently binding directly to the converter, that's not actually the case. You are binding to the data context without specifying a Path
so you can use access the whole thing.