Windows 8.1 Store App静态资源转换器 - 无法解析资源

时间:2015-03-06 17:24:27

标签: c# xaml

 <ListView ItemsSource="{Binding Collection}" 
                  SelectedValue="{Binding Selected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                  Height="Auto" 
                  Width="Auto" 
                  VerticalAlignment="Bottom" HorizontalAlignment="Left">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Border BorderBrush="Aqua" BorderThickness="2">
                        <StackPanel Width="Auto" 
                                    Height="Auto" 
                                    Background="Blue">
                            <TextBlock Text="{Binding colId, Converter={StaticResource StringFormatConverter}, ConverterParameter='Collection ID: {0}'}"/>
                            <TextBlock Text="{Binding Description, Converter={StaticResource StringFormatConverter}, ConverterParameter='Description: {0}'}"/>
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

C#代码字符串格式转换器类

 public sealed class StringFormatConverter : IValueConverter
 {
   public object Convert(object value, Type targetType, object parameter,  string language)
   {
     if (value == null)
      return null;

     if (parameter == null)
      return value;

     return string.Format((string)parameter, value);
   }

  public object ConvertBack(object value, Type targetType, object parameter,
    string language)
  {
   throw new NotImplementedException();
  }
}

上面的类应该处理我想在UI中显示的格式,但是我得到'资源无法解析'。

1 个答案:

答案 0 :(得分:1)

在包含listview的页面/用户控件xaml中,您必须先将转换器定义为静态资源,然后才能使用它。因此,如果您的转换器位于名称空间 dummynamespace 中,请将其放在以下任一位置:

<Page xmlns:common="using:<dummynamespace>">
<Page.Resources>
<common:StringFormatConverter x:Key="StringFormatConverter" />
</Page.Resources>

<ListView ItemsSource="{Binding Collection}" 
              SelectedValue="{Binding Selected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              Height="Auto" 
              Width="Auto" 
              VerticalAlignment="Bottom" HorizontalAlignment="Left">
<ListView.Resources>
<common:StringFormatConverter x:Key="StringFormatConverter" />
</ListView.Resources>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Aqua" BorderThickness="2">
                    <StackPanel Width="Auto" 
                                Height="Auto" 
                                Background="Blue">
                        <TextBlock Text="{Binding colId, Converter={StaticResource StringFormatConverter}, ConverterParameter='Collection ID: {0}'}"/>
                        <TextBlock Text="{Binding Description, Converter={StaticResource StringFormatConverter}, ConverterParameter='Description: {0}'}"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>