Reputation: 19
How do I convert string values to integers and back using IValueConverter?
This is my ItemTemplate below:
<Application.Resources>
<DataTemplate x:Key="myTemplate">
<WrapPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding FirstName}"/>
<Label />
<TextBlock Text="{Binding LastName}"/>
</WrapPanel>
</DataTemplate>
</Application.Resources>
This is my Combobox which is bound to the ItemTemplate:
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,90,267,0"
Name="comboID" ItemsSource="{Binding}" VerticalAlignment="Top"
Width="208" ItemTemplate="{StaticResource myTemplate}" />
And a DataGrid which displays:
<DataGridTemplateColumn x:Name="pIDColumn" Header="Person ID" Width="auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=pID, Converter= {StaticResource myConverter}}"/>
<DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn x:Name="rolesColumn" Header="Roles" Width="auto" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Roles}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
IValueConverter which is not converting!!
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string a = (string)value;
int b;
int.TryParse(a, out b);
return b;
}
public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
Upvotes: 0
Views: 14593
Reputation: 3135
Like was said in the other answer, you are doing it backwards. The Convert side of an IValueConverter is meant for converting from the source property to what is in the bound element, in your case a textbox. You need to do your parsing on the ConvertBack side because that is what takes what is in the textbox (a string) and converts it back to a number.
public class IntToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
int ret = 0;
return int.TryParse((string)value, out ret) ? ret : 0;
}
}
Upvotes: 0
Reputation: 21261
You are converting the wrong way around. Convert()
takes the binding source as input (int
in your case), and outputs what the xaml is expecting (string
).
But you don't even need a converter. You can bind straight to an int
and WPF will automatically call ToString()
on it to display it as text.
Upvotes: 3