通过 ElementName/RelativeSource 进行的绑定在 ListBox 上失败,但适用于其中的项目

问题描述 投票:0回答:1

我有一个简单的 WPF 测试应用程序。 它是一个带有

Window
Grid
,持有一个显示
ListBox
元素的
Image
。 当我第一次运行它时,图像扩展到窗口的边界之外,因此我将它们的
MaxWidth
属性绑定到窗口的
ActualWidth
。 无论我是通过
ElementName
还是
RelativeSource

绑定,这都有效

但是,当我采用完全相同的绑定并将其从每个单独的

Image
元素向上移动到包含的
ListBox
(或到
Grid
)时,它没有任何效果。 图像(或列表框)再次超出窗口的限制。

输出窗口中没有绑定警告。 它什么也没做。

但是,如果我在这 3 个位置中的任何一个位置放置硬编码宽度值(例如“400”),它就可以正常工作。 这只是在更高级别停止工作的绑定。

谁能告诉我为什么? 理解为什么会在很多其他绑定情况下帮助我

这是 XAML,其工作绑定在

Image
元素上

<Window x:Class="MVVM_RenderPhotos.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MVVM_RenderPhotos"
        xmlns:vm="clr-namespace:MVVM_RenderPhotos.ViewModels"
        xmlns:models="clr-namespace:MVVM_RenderPhotos.Models"
        d:DataContext="{d:DesignInstance {x:Type vm:MainWindowVm}}"
        mc:Ignorable="d"
        x:Name="Root"
        Title="MainWindow" Height="800" Width="400">

    <Grid x:Name="MainGrid">
        <ListBox ItemsSource="{Binding Scans}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type models:Scan}">
                    <Grid >
                        <Image MaxWidth="{Binding ElementName=Root, Path=ActualWidth}" 
                               Source="{Binding Thumbnail}" />
                    </Grid>
                </DataTemplate>

            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
wpf data-binding
1个回答
0
投票

无需绑定

MaxWidth
(或
Width
)。

只需禁用列表框的水平滚动即可。

<ListBox ItemsSource="{Binding Scans}"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type models:Scan}">
            <Image Source="{Binding Thumbnail}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
© www.soinside.com 2019 - 2024. All rights reserved.