C# Windows Phone更改列表框中文本块的文本

C# Windows Phone更改列表框中文本块的文本,c#,xaml,windows-phone-7,windows-phone-8,listbox,C#,Xaml,Windows Phone 7,Windows Phone 8,Listbox,我在windows phone应用程序的xaml页面中有一个列表框 listbox的itemsource设置为来自服务器的数据 我需要根据从服务器接收到的数据设置这个列表框中的文本块/按钮的文本 我不能直接绑定数据,也不能更改来自服务器的数据 我需要这样做:- if (Data from server == "Hey this is free") { Set textblock/button text to free } else { Set textblock/button t

我在windows phone应用程序的xaml页面中有一个列表框

listbox的itemsource设置为来自服务器的数据

我需要根据从服务器接收到的数据设置这个列表框中的文本块/按钮的文本

我不能直接绑定数据,也不能更改来自服务器的数据

我需要这样做:-

if (Data from server == "Hey this is free")
    { Set textblock/button text to free }
else
    { Set textblock/button text to Not Free/Buy }
来自服务器的数据(对于这个特定元素)可以有2-3种以上的类型,例如,它可以是$5、$10、$15、免费或其他任何类型

因此,只有在“免费”的情况下,我才需要将文本设置为“免费”,否则将其设置为“不免费/购买”

如何访问列表框中的此文本块/按钮?

您可以定义:

并在xaml中使用

<TextBlock Text="{Binding Text, Converter={StaticResource PriceConverter}}">

您应该使用
转换器。以下是如何:

首先声明一个实现
IValueConverter
的类。 在这里,您将测试从服务器接收的值并返回适当的值

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();
    }
}
在页面顶部,添加名称空间声明:

xmlns:local="clr-namespace:namespace-where-your-converter-is"
声明转换器:

<phone:PhoneApplicationPage.Resources>
    <local:PriceConverter x:Key="PriceConverter"/>
</phone:PhoneApplicationPage.Resources>

并在文本块上使用它:

<TextBlock Text="{Binding Price,Converter={StaticResource PriceConverter}}"/>


我声明了转换器,但它说“名称空间前缀“local”未定义”和“Silverlight project不支持PriceConverter”是的,您需要声明转换器所属的名称空间。在页面顶部,添加“xmlns:local=“clr namespace:yourprojectname”。我编辑了我的答案以反映这一点。非常感谢,我发现了这一点,感谢谷歌;)非常感谢您的快速回复
<TextBlock Text="{Binding Price,Converter={StaticResource PriceConverter}}"/>