【问题标题】:WPF : How to bind StackPanel height (which is auto) to ImageControl height?WPF:如何将 StackPanel 高度(自动)绑定到 ImageControl 高度?
【发布时间】:2011-04-19 20:10:06
【问题描述】:

我在设计 (xmal) 中创建了具有自动高度和宽度的 stackPanel。将加载时代码中的图像控件列表动态添加到 stackPanel。现在它工作正常。但是当我尝试调整窗口大小时,虽然堆栈面板由于自动而调整大小,但不是图像控制。

如何将 stackpanel 的实际高度动态绑定到图像控制高度,(所以当 stakpanl 高度改变时,图像控制也应该改变!!)。

谢谢

【问题讨论】:

    标签: binding


    【解决方案1】:

    使用ViewBox

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Viewbox MaxWidth="500" MaxHeight="500" Name="vb1">
            <Image Source="tulip_farm.jpg"/>
        </Viewbox>    
    </StackPanel>
    

    How to: Apply Stretch Properties to the Contents of a Viewbox

    或者你可以使用如下绑定:

    <StackPanel x:Name="MyStackPanel">
        <Image Source="C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg" Stretch="Uniform" Height="{Binding ElementName=MyStackPanel, Path=ActualHeight}"></Image>
    </StackPanel>
    

    【讨论】:

    • 感谢您的回复。但就我而言,我在后面的代码中动态添加了 N 个 Image 控件。不在 Xmal 中。那么在这种情况下我们如何绑定呢?
    • 下面是代码片段,//读取图像文件后,将其添加到堆栈面板 foreach (string strFile in ArrStrFiles) { // 此处显示文件名 BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.UriSource = new Uri(strFile); bi.EndInit();图片 img = new Image(); img.Source = bi; img.Width = 170; img.Height = stkPanl.ActualHeight; img.Stretch = 拉伸填充; img.Horizo​​ntalAlignment = Horizo​​ntalAlignment.Stretch; img.VerticalAlignment = VerticalAlignment.Stretch;
    • 边框边框 = new Border(); border.Background = new SolidColorBrush(Colors.Black); border.BorderThickness = 新厚度(5); border.BorderBrush = new SolidColorBrush(Colors.Black);边框.儿童 = img; stkPanl.Children.Add(边框); }
    • 请用代码更新您的问题。它会更具可读性。
    • 请在上面的 cmets 中找到代码片段。虽然它看起来像段落:) 由于字符限制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多