在datatemplate中更改Image的宽度和高度

时间:2013-04-30 12:44:17

标签: xaml winrt-xaml

我在datatemplate中有一个图像。我想根据特定条件改变它的高度和宽度。我怎样才能做到这一点?

我的XAML代码:

    <ListBox x:Name="options_stack" HorizontalAlignment="Left" Margin="198,569,0,33" Width="603" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollMode="Auto" Height="123" Style="{StaticResource ListBoxStyle}" ItemContainerStyle="{StaticResource ListBoxItemStyle}" >
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image x:Name="options_image" Source ="{Binding}" Stretch="Fill" Width="123" Height="123" MaxHeight="123" MaxWidth="123" Tapped="apply_accessory"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

1 个答案:

答案 0 :(得分:3)

选项1

由于您是绑定源属性,我将创建一个数据结构(用作DataContext)来保存SourceWidthHeight属性,然后绑定它们:

<Image x:Name="options_image"
       Source ="{Binding Source}"
       Width="{Binding Width}" Height="{Binding Height}"
       MaxWidth="{Binding Width}" MaxHeight="{Binding Height}"
       Stretch="Fill" Tapped="apply_accessory"/>

选项2

另一种选择是创建不同的 DataTemplates DataTemplateSelector ,以便在满足特定条件时应用。

DataTemplateSelector ref:http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx

选项3

如果你不喜欢上述两个选项,你可以采用另一种方式。在我的上一部作品中(任务,如果你想看一下,你可以看到我的个人资料中的链接)我需要为不同的ListViewItems显示不同的颜色。我不想在我的Task模型中创建一个新属性来保存颜色,或者只为此TemplateSelector创建一个新属性。所以我创建了一个简单的IValueConverter,它使用已存在的Priority对象属性并返回其颜色。然后我把它绑起来:

<Border Background="{Binding Priority, Converter={StaticResource priorityToColorConverter}}"/>

XAML为您提供了许多实现您想要的方法,您可以选择最好,最干净的方法来解决您所面临的问题。