I have a ListView
that has a Grid
with two columns and many rows. Each row has a TextBlock
in each column with each Text
property binded to a value in ListView's ItemSource
. I need to do some converting of the text in the second TextBlock
depending on the value in the first TextBlock
. How can I get the value of the first text box to the converter?
Here is what I have so far:
XAML:
<UserControl.Resources>
<local:ValueStringConverter x:Key="valueStringConverter" />
</UserControl.Resources>
<ListView Name="theListView" ItemsSource="{Binding ItemCollection}" SelectedItem="{Binding SelectedItem}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Grid.Row="1" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Key}" Grid.Column="0" Margin="0,0,10,0" />
<TextBlock Text="{Binding Path=Value, Converter={StaticResource valueStringConverter}}" TextWrapping="Wrap" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code of ValueStringConverter
:
public class ValueStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string name = (string)value;
name = name.Replace("$$", " ");
name = name.Replace("*", ", ");
name = name.Replace("##", ", ");
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You can't pass more than one value to the "regular" value converter. You could go with IMultiValueConverter and define the binding as MultiBinding.
Or you can create a IValueConverter that takes the entire object in the DataContext, cast the object to its type, take the Value and Key and return the string you need.
On your second textblock define the binding as
<TextBlock Text="{Binding Converter={StaticResource valueStringConverter}"/>
And your converter as:
public class ValueStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
MyDataContextObjectType obj= (MyDataContextObjectType)value;
var name= obj.Name;
var key = obj.Key;
//here you have both Name and Key, build your string and return it
//if you don't know the type of object in the DataContext, you could get the Key and Name with reflection
name = name.Replace("$$", " ");
name = name.Replace("*", ", ");
name = name.Replace("##", ", ");
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}