【发布时间】:2011-08-30 19:18:45
【问题描述】:
我想创建一个继承 WPF Grid 并具有以下功能的 自定义控件:
- 它必须有一些默认行
- 它必须有一些子控件在 那些行(主要是按钮和线条) 默认
- 非默认内容 必须可由设计师编辑或 在插入控件的窗口的 xaml 中写入内容
我尝试继承 Grid 并在构造函数中添加内容,但是一旦我通过设计器添加更多内容,默认内容就会丢失。我已经尝试了很多事情,但我无法做到。甚至可能吗?我怎么能做到这一点?
【问题讨论】:
我想创建一个继承 WPF Grid 并具有以下功能的 自定义控件:
我尝试继承 Grid 并在构造函数中添加内容,但是一旦我通过设计器添加更多内容,默认内容就会丢失。我已经尝试了很多事情,但我无法做到。甚至可能吗?我怎么能做到这一点?
【问题讨论】:
马丁,你不能那样做。 Grid 是一种面板,内容为子属性。因此,如果您在 XAML 设计器中添加任何内容,它将被重新调整。
但是您可以覆盖子属性,并将其添加到您的类 <ContentProperty("PropertyName")> 中,就像示例中一样 -
例如:
'Code:
<ContentProperty("Children")> _
Public Class MyGrid
Public Overloads ReadOnly Property Children As UIElementCollection
Get
Return Me.ContentGrid.Children
End Get
End Property
End Class
'Markup
<Grid x:Class="MyGrid" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Content="Button" Height="23" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" />
<Button Content="Button" Height="23" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Grid.Row="2" />
<Button Content="Button" Height="23" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Grid.Row="1" />
<Grid Name="ContentGrid" Grid.RowSpan="3"></Grid>
</Grid>
【讨论】: