Windows Phone 更改列表框中文本块的文本
本文关键字:文本 中文 列表 Phone Windows | 更新日期: 2023-09-27 18:30:50
我的 Windows Phone 应用程序的 xaml 页面中有一个列表框。
列表框的项源设置为来自服务器的数据。
我需要根据从服务器接收的数据设置此列表框中的文本块/按钮的文本。
我不能直接绑定数据,也不能更改来自服务器的数据。
我需要做这样的事情:-
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 美元、免费或其他任何类型。
所以只有在免费的情况下,我需要将文本设置为免费,否则将其设置为不免费/购买。
如何访问列表框中的此文本块/按钮?
你应该使用Converter
。方法如下:
首先声明一个实现 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();
}
}
在页面顶部,添加 Namepace 声明:
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}}"/>
您可以定义一个值转换器:
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();
}
}
并在 XAML 中使用
<TextBlock Text="{Binding Text, Converter={StaticResource PriceConverter}}">