DataBinding GridView C#windows存储应用

时间:2013-01-22 15:58:39

标签: c# windows-store-apps

我有一个如下定义的DataTemplate

<DataTemplate x:Key="IconTextDataTemplate">
        <StackPanel Orientation="Horizontal" Width="220" Height="60">
            <Border Background="#66727272" Width="40" Height="40" Margin="10">
                <Image Source="/SampleImage.png" Height="32" Width="32" Stretch="UniformToFill"/>
            </Border>
            <StackPanel Orientation="Vertical" VerticalAlignment="Center">
                <TextBlock Text="{Binding Path=Title}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis" />
                <TextBlock  Text="{Binding Path=NumberOfPhotos}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>

然后我有一个使用DataTemplate的GridView

<GridView x:Name="gv" Grid.Row="0" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Top" 
                  Width="Auto" Height="Auto" SelectionMode="Multiple" ItemTemplate="{StaticResource IconTextDataTemplate}" ItemsSource="{Binding}">
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapGrid MaximumRowsOrColumns="8" 
                  VerticalChildrenAlignment="Top" HorizontalChildrenAlignment="Center" />
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
        </GridView>

然后我将GridViews dataContext设置为集合

gv.DataContext = setCollection;

对象setCollection是具有NumberOfPhotos和Title属性的对象的集合,因此绑定

<TextBlock Text="{Binding Path=Title}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis" />
                <TextBlock  Text="{Binding Path=NumberOfPhotos}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>

的工作原理。但是,该对象没有ImageSource的属性

<Image Source="/SampleImage.png" Height="32" Width="32" Stretch="UniformToFill"/>

我希望绑定到由两个字符串和对象属性组成的复合结构,而不是绑定到对象的属性,如下所示:

ImageSource = "/files/thumbnails/" + {Binding Path=Title} + fileType;

因此,在评估时,ImageSource变为

/files/thumbnails/titleOfObject.png

其中titleOfObject等于此处的值

<TextBlock Text="{Binding Path=Title}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis" />  

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

最好以ViewModel的形式查看绑定对象。从概念上讲,这意味着ViewModel对象的工作是为视图准备数据。这包括按摩标题以绑定到Source属性。因此,在您的对象(或派生对象,或对象的正式ViewModel)上,创建一个为您执行该计算的属性。

public string TitleImageSource
{
    get
    {
        return string.Format(@"/files/thumbnails/{0}{1}", this.Title, fileType);
    }
}

然后绑定到Image中的该属性。

另一种选择是为绑定创建转换器。转换器可能类似于:

public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return string.Format(@"/files/thumbnails/{0}{1}", value, parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return string.Empty;
    }
}

然后在Image标签上的Source绑定上引用该转换器。