Reputation: 823
I'm trying to bind to a single item from a collection but I need to be able to pass in a value from the element as the index. Below is a sample of what I'm trying to accomplish.
ViewModel
public Dictionary<string, string> ListOfString = new Dictionary<string, string>
{
{"0", "TextToDisplay" }
};
View
<TextBox Tag="0" Text="{Binding ListOfString[Self.Tag]}" />
I'm not sure how to get the value of TextBox.Tag
and pass it to ListOfString
Upvotes: 0
Views: 2941
Reputation: 9944
You could use a MultivalueConverter
in which you will pass the ListOfStrings
Dictionary
and the Tag
property of the TextBox
like so:
<Window.Resources>
<ns:ValuFromDicConverter x:Key="ValuFromDicConverter"/>
</Window.Resources>
<Grid>
<TextBox Tag="0" x:Name="tb">
<TextBox.Text>
<MultiBinding Converter="{StaticResource ValuFromDicConverter}">
<Binding Path="ListOfString"/>
<Binding ElementName="tb" Path="Tag"></Binding>
</MultiBinding>
</TextBox.Text>
</TextBox>
</Grid>
the converter will simply get the corresponding value in the Dictionary
:
public class ValuFromDicConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null) return null;
return (values[0] as Dictionary<string, string>)[values[1].ToString()];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
and don't forget to define your dictionary as a property and set the DataContext
private Dictionary<string, string> _listOfString = new Dictionary<string, string>
{
{"0", "TextToDisplay" }
};
public Dictionary<string, string> ListOfString
{
get
{
return _listOfString;
}
set
{
if (_listOfString.Equals(value))
{
return;
}
_listOfString = value;
}
}
Upvotes: 2