3

我在数据模板中有一个图像。我想根据某些条件改变它的高度和宽度。我怎样才能做到这一点?

我拥有的 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>
4

1 回答 1

3

选项1

由于您正在绑定源属性,因此我将创建一个数据结构(用作 DataContext)来保存和属性Source,然后绑定它们:WidthHeight

<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

另一种选择是创建不同的DataTemplatesDataTemplateSelector以在满足某些条件时应用。

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

选项 3

如果您不喜欢上述两个选项,则可以使用另一种方法。在我的上一部作品中(Taskin,如果你想看看,你可以在我的个人资料中看到链接)我需要为不同的ListViewItems. 我不想在我的Task模型中创建一个新属性来保存颜色或TemplateSelector仅仅为此。所以我创建了一个简单的IValueConverter替代方法,它使用已经存在的Priority对象属性并返回它的颜色。然后我像这样绑定它:

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

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

于 2013-04-30T13:05:49.573 回答