【问题标题】:Encapsulating repeated layout in WPF在 WPF 中封装重复布局
【发布时间】:2011-05-26 11:36:31
【问题描述】:

在我绑定到视图模型的数据模板中,我有一个像这样的网格:

<Grid> 
 .  
 .  <!--Row & Col Definitions...-->
 .
 <TextBlock Text="Some Label" Style="{DynamicResource TextBlockLabelStyle}" />
 <TextBlock Grid.Column="1" Text="{Binding SomeValue, Mode=OneWay}"/>
 <Border Style="{DynamicResource SeparatorStyle}" />

 <TextBlock Grid.Row="1" Text="Some Label" Style="{DynamicResource TextBlockLabelStyle}" />
 <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding SomeValue, Mode=OneWay}"/>
 <Border Grid.Row="1" Style="{DynamicResource SeparatorStyle}" />   

 <TextBlock Grid.Row="2" Text="Some Label" Style="{DynamicResource TextBlockLabelStyle}" />
 <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding SomeValue, Mode=OneWay}"/>
 <Border Grid.Row="2" Style="{DynamicResource SeparatorStyle}" />   
</Grid> 

我认为添加这种重复模式(TextBlock 用于标签,TextBlock 用于值,水平规则)变得乏味,并认为最好将其封装到 UserControl 中,例如“GridRow”:

<UserControl x:Class="GridRow">
  <TextBlock Text="{Binding LabelText}" Style="{DynamicResource TextBlockLabelStyle}" />
  <TextBlock Grid.Column="1" Text="{Binding ValueText, Mode=OneWay}"/>
  <Border Style="{DynamicResource SeparatorStyle}" />
</UserControl>

然后我可以这样做:

<Grid>
  <GridRow LabelText="Some Label" ValueText="{Binding SomeValue}"/>
  <GridRow Grid.Row="1" LabelText="Some Label2" ValueText="{Binding SomeValue2}"/>
  <GridRow Grid.Row="2" LabelText="Some Label3" ValueText="{Binding SomeValue3}"/>
</Grid>

并让用户控件绑定到 LabelText 和 ValueText 属性,也许通过模板绑定?

我的问题是如何做到这一点,如果这是正确的做法,或者是否可以使用样式或数据模板来做到这一点?

【问题讨论】:

    标签: wpf binding datatemplate


    【解决方案1】:

    不幸的是,这并不容易实现。网格布局查看其直接子级的 Grid.Row 和 Grid.Column 属性,以创建所需的布局。因此,将 UI 控件嵌套在另一个 Grid 中会破坏布局。

    几个选项,这篇博文解决了这个问题,但很复杂:

    http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/

    这里有一个不错的Auto-grid,我没用过,但是看起来还不错:

    http://whydoidoit.com/2010/10/06/automatic-grid-layout-for-silverlight/

    问候, 科林 E.

    【讨论】:

    • 它不必在网格内。我可以很容易地将它们放入一个垂直的堆栈面板中。我只是想要一种方法来分解常用的标签/值/分隔符 UI 元素,但能够参数化它们。 PS 这些属性不是集合的一部分,它们只是我想以类似方式显示的视图模型上的属性。
    • 哦,我明白了。我认为您将不得不修改您的视图模型以将这些重复的属性包装到一个类中,然后从您当前的视图模型中公开这些属性的集合。然后,您可以将其绑定为 ItemsControl 的 ItemsSource,并使用 ItemControl.ItemTemplate 描述如何呈现每个项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2011-03-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多