Avalon System.Windows.Data.IValueConverter
There I was with an array of keywords (string[]) in one hand and a single TextBox in the other hand, wanting to bind them.
How did I do it? Well, the IValueConverter seems to be the best way to go!
The XAML where the binding and converter is specified:
<?
Mapping XmlNamespace="Recette" ClrNamespace="Microsoft.Samples.RecipeCatalog.Recette" ?>
<PageFunction x:Class="Microsoft.Samples.RecipeCatalog.Recette.RecipePage"
x:TypeArguments="Recipe"
xmlns="https://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="https://schemas.microsoft.com/winfx/xaml/2005"
xmlns:Recette="Recette "
Loaded="OnLoaded">
…
<DockPanel>
< DockPanel.Resources >
< Recette:KeywordsToStringConverterx:Key="Converter" />
</ DockPanel.Resources >
<TextBlock DockPanel.Dock="Left">Keywords:</TextBlock>
<TextBox DockPanel.Dock="Right"
Text ="{Binding Path=RecipeKeywords, Mode=TwoWay, UpdateSourceTrigger=LostFocus, Converter={StaticResource Converter} }" />
</DockPanel>
…
</PageFunction>
Microsoft.Samples.RecipeCatalog.Recette.RecipeKeywords is an instance property that returns the array of strings (keywords).
The converter code:
public class KeywordsToStringConverter : IValueConverter
{
public object Convert(object o, Type type, object parameter, System.Globalization.CultureInfo culture)
{
// Array of keywords (string[]) to string of keywords separated by space
string[] keywordsArray = o as string[];
if (keywordsArray == null || type != typeof(string))
return Binding.DoNothing;
StringBuilder keywordsInOneString = new StringBuilder();
foreach (string s in keywordsArray)
{
keywordsInOneString.Append(s);
keywordsInOneString.Append(' ');
}
return keywordsInOneString.ToString();
}
public object ConvertBack(object o, Type type, object parameter, System.Globalization.CultureInfo culture)
{
// String of keywords separated by space to Array of keywords (string[]).
if (!(o is string) || type != typeof(string[]))
return Binding.DoNothing;
return (o as string).Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries) ;
}
}
I thought I would share this in case you find yourself in the same situation I was in this morning.
Good luck!