我将回答这个问题:它可行吗?我的初步想法是,我不想计算调整大小。我希望使用网格来解决这个问题。因此,我将忽略所有其他关于是否应该是另一种控件类型或者这是否是“正确”的方法的问题。
接下来...首先,我使用一个控件模板,其中
uxMainContentGrid是在添加项目时要修改的网格。
<Style TargetType="">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="">
<Border Background=""
BorderBrush=""
BorderThickness=""
Height=""
Width="">
<Grid x:Name="uxMainContentGrid">
<Grid.ColumnDefinitions>
<!-- Columns and ratio is set in code behind -->
</Grid.ColumnDefinitions>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
我用来设置宽度比例的项目看起来像这样。
Public Class RatioItem
Public Property Value As Double
Public Property Brush As Brush
End Class
而且,RatioItems 是通过这个依赖属性添加的,默认值是一个空的 RatioItems 列表。
Public Shared ReadOnly RatioItemsProperty As DependencyProperty = _
DependencyProperty.Register("RatioItems", GetType(IEnumerable(Of RatioItem)),
GetType(RatioPresenterControl),
New FrameworkPropertyMetadata(New List(Of RatioItem), AddressOf OnRatioItemsPropertyChanged))
该依赖属性具有以下值更改回调方法。当您绑定到依赖属性时,此回调会在模板应用之前触发。仅当控件模板已设置时,此回调才会重构网格列。
Public Shared Sub OnRatioItemsPropertyChanged(sender As Object, e As DependencyPropertyChangedEventArgs)
If (_MainContentGrid IsNot Nothing) Then
Dim ratioItems As IEnumerable(Of RatioItem) = TryCast(e.NewValue, IEnumerable(Of RatioItem))
ReconstructGridColumns(ratioItems, _MainContentGrid)
End If
End Sub
以下代码在应用控件模板时检索网格。这里的关键是存储网格,以便在RatioItems属性更改后可以稍后访问它。当应用模板时,绑定已经生效,因此网格列已构建。
Public Overrides Sub OnApplyTemplate()
MyBase.OnApplyTemplate()
_MainContentGrid = TryCast(Me.Template.FindName("uxMainContentGrid", Me), Grid)
ReconstructGridColumns(Me.RatioItems, _MainContentGrid)
End Sub
这个方法执行所有的“构造”操作...
Private Shared Sub ReconstructGridColumns(ByVal ratioItems As IEnumerable(Of RatioItem), ByVal mainContentGrid As Grid)
Dim newContent As Rectangle
Dim columnCount As Integer = 0
mainContentGrid.ColumnDefinitions.Clear()
For Each item In ratioItems
mainContentGrid.ColumnDefinitions.Add(New ColumnDefinition() With {.Width = New GridLength(item.Value, GridUnitType.Star)})
newContent = New Rectangle() With {.Name = "item" & columnCount, .Fill = item.Brush}
mainContentGrid.Children.Add(newContent)
Grid.SetColumn(newContent, columnCount)
columnCount += 1
Next
End Sub
就是这样。它可以完成。现在讨论的是是否这是“正确”的方法... :)