Reputation: 1532
I have a listbox in my xaml page in my windows phone app.
the itemsource of the listbox is set to data coming from the server.
I need to set the text of a textblock/button inside this listbox according to data received from the server.
I cant bind the data directly, neither can I change the data coming from the server.
I need to do something like this:-
if (Data from server == "Hey this is free")
{ Set textblock/button text to free }
else
{ Set textblock/button text to Not Free/Buy }
data from server (for this particular element) can have more than 2-3 types, for example it can be $5, $10, $15, Free or anything else
so only in case of free, I need to set text to free otherwise set it to Not Free/Buy.
How can I access this textblock/button inside the listbox?
Upvotes: 1
Views: 782
Reputation: 15268
You should use a Converter
. Here is how:
Start by declaring a class that implements IValueConverter
.
This is where you will test the value received from the server and return the appropriate value.
public sealed class PriceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value.ToString() == "Hey this is free")
{
return "free";
}
else
{
return "buy";
}
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
At the top of your page, add the Namepace declaration:
xmlns:local="clr-namespace:namespace-where-your-converter-is"
Declare the Converter:
<phone:PhoneApplicationPage.Resources>
<local:PriceConverter x:Key="PriceConverter"/>
</phone:PhoneApplicationPage.Resources>
And use it on the TextBlock:
<TextBlock Text="{Binding Price,Converter={StaticResource PriceConverter}}"/>
Upvotes: 2
Reputation: 9230
You can define a value converter:
public class PriceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return String.Empty;
var text = (string) value;
return text.Contains("Free") ? "text to free" : text;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
and use in in your xaml
<TextBlock Text="{Binding Text, Converter={StaticResource PriceConverter}}">
Upvotes: 0