【问题标题】:Changing width and height of Image inside a datatemplate更改数据模板内图像的宽度和高度
【发布时间】:2013-04-30 12:44:17
【问题描述】:

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

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

【问题讨论】:

    标签: xaml winrt-xaml


    【解决方案1】:

    选项 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

    另一种选择是创建不同的 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 为您提供了多种方式来实现您想要的功能,您可以选择最好、最简洁的方式来解决您面临的问题。

    【讨论】:

    • 我试过绑定高度和宽度。但是当我在一个方法中更改它们时,它不起作用......在我的方法中我写了这个: optionDimensions op = new optionDimensions();操作高度 = 123;操作宽度 = 123;我错过了什么?
    • 你实现INotifyPropertyChanged了吗?如果您使用的是optionDimensions 列表,请改用ObservableCollection&lt;optionDimensions&gt;
    • 是的,它与 ObservableCollection 一起使用。谢谢你
    • 很高兴它成功了。请参阅我添加的另一种选择。将来可能对您有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多