【问题标题】:Windows Phone change text of textblock in listboxWindows Phone 更改列表框中文本块的文本
【发布时间】:2013-09-11 07:33:27
【问题描述】:

我的 Windows Phone 应用程序的 xaml 页面中有一个列表框。

列表框的 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、Free 或其他任何东西

所以只有在免费的情况下,我需要将文本设置为免费,否则将其设置为非免费/购买。

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

【问题讨论】:

    标签: c# xaml windows-phone-7 windows-phone-8 listbox


    【解决方案1】:

    您应该使用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 上使用它:

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

    【讨论】:

    • 我声明了转换器,但它显示“名称空间前缀“本地”未定义”和“Silverlight 项目不支持 PriceConverter”
    • 是的,需要声明Converter所属的命名空间。在页面顶部,添加“xmlns:local="clr-namespace:yourprojectname"。我编辑了我的答案以反映这一点。
    • 非常感谢,感谢谷歌,我明白了;)非常感谢您的快速回复
    【解决方案2】:

    你可以定义一个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();
            }
        }
    

    并在您的 xaml 中使用

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

    【讨论】:

      猜你喜欢
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多