wpf Grid best practices

梦想的初衷 提交于 2019-12-10 18:34:16

问题


I have a grid that contains many labels, combo boxed, and text boxes. I'm putting both a label and combo box in each cell.

What is the best practice: 1. Place the Combo Box and the label in a stack panel and then place it a cell 2. Simply put the two controls directly in a grid cell

What are the advantages and disadvantages for both approaches?

Thank you


回答1:


The disadvantage of putting both controls together in the same cell is that the second one will be superimposed on top of the first (which you'd have noticed if you'd tried it), and the only way to fix that is by giving them bizarre margins or putting them both in a StackPanel, which is why everybody just puts them in a StackPanel.

I suggest this: Define a style as shown below, and put it in some global thing included in App.xaml (or in App.xaml itself, if you're in a piratical frame of mind):

<Style x:Key="FieldStyle" TargetType="HeaderedContentControl">
    <Setter Property="Margin" Value="8,3" />
    <Setter Property="MinWidth" Value="300" />
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="HeaderedContentControl">
                <StackPanel Orientation="Vertical">
                    <Label 
                        FontWeight="Bold" 
                        Content="{TemplateBinding Header}" 
                        />
                    <ContentPresenter 
                        Margin="8,0,0,0"
                        />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And use it like this:

<HeaderedContentControl 
    Header="Contact Name"
    Grid.Row="0"
    Grid.Column="0"
    Style="{StaticResource FieldStyle}" 
    >
    <TextBox Text="{Binding ContactName}" />
</HeaderedContentControl>

<HeaderedContentControl 
    Header="Contact Phone"
    Grid.Row="1"
    Grid.Column="0"
    Style="{StaticResource FieldStyle}" 
    >
    <TextBox Text="{Binding ContactPhone}" />
</HeaderedContentControl>

This lets you change the formatting of all your label/control pairs easily. I'd usually just slap a mess of those things in a StackPanel or WrapPanel myself, but if a Grid makes sense for your layout, by all means go with it.

The template in that style could and arguably should be TemplateBinding a lot more stuff than it is, but I got tired of typing and it's got all I'm actually going to use.



来源:https://stackoverflow.com/questions/38209202/wpf-grid-best-practices

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