WPF XAML: How to automatically scale down children of a component in XAML?

时光毁灭记忆、已成空白 提交于 2019-12-18 09:47:16

问题


Here's my problem:

xaml file 1: a templated list control

<ItemsControl ItemSource={Binding myUIrelatedDataList}/>
   <ItemsControl.ItemTemplate>
       <DataTemplate>
           <my:DynamicUIPresenter Width="160" Height="80"/>
           <!-- here, I want to specify my desired size to which i want to
                scale down the generated UIElements -->
       </DataTemplate>
   </ItemsControl.ItemTemplate>
<ItemsControl/>

xaml file 2: the item template

 <Border BorderBrush="Black" BorderThickness="1">
    <Border Child="{Binding Path=., Converter={StaticResource DynaUIConverter}}"/>
 </Border>

The problem is that I do not know anything about the myUIrelatedDataList and what exact kind of UIElements the DynaUIConverter is producing. The DynaUIConverter usually produces a set of Stackpanels nested in each other and containing TextBoxes, Buttons, etc. These panels do not have a Width or Height set, which I might not be able to fix.

I think I need to measure the minimum size requirements of the generated UI and dynamically apply a ScaleTransform to the produced UI, or maybe better to the Border containing the generated UI.

I tried this in code behind, but the scaling did not work correctly, since I was not able to understand how/if width and height propagation from children to parents really works. And I also ran into some recursion problem, which made the code in the end quite inefficient.

The Question now is: Can I do this downscaling of a child element directly/easily in XAML?


回答1:


I believe a Viewbox will do what you want. It has a single child which is always given its desired size, and it applies a ScaleTransform to the child so that it fits inside the Viewbox. By default it will apply a uniform stretch, but you can change this by setting the Stretch property.

Something like this:

<ItemsControl ItemsSource="{Binding myUIrelatedDataList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Viewbox Width="160" Height="80">
                <my:DynamicUIPresenter />
            </Viewbox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>



回答2:


Yeah Set VerticalStretch for your repeating element to Stretch, that should automatically make them behave as part of the list.

As for the list, if it blows out of your container, put it in a Dockpanel.

Sorry I couldn't understand what you're doing with the scale transform :) ... but it does sound like hammering a screw in.

Maybe post a screenshot if that doesn't do it to help us understand.



来源:https://stackoverflow.com/questions/3369911/wpf-xaml-how-to-automatically-scale-down-children-of-a-component-in-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!