拥有同时支持s 和现有内容的用户控制 ( )是否可能并且是个好主意?我知道s 应该只在您从 Control ( ) 继承时使用,但我发现如果您的 UserControl.xaml 为空,您也可以使用它们。public MyControl: UserControl
ControlTemplate
ControlTemplate
public MyControl: Control
UserControl
想象一下,我有一个控件,它有两个并排的矩形,如下所示:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid ShowGridLines="true" Height="100" Width="100">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Rectangle Name="left" Grid.Column="0" Height="90" Fill="LightBlue"/>
<Rectangle Name="right" Grid.Column="1" Height="100" Fill="LightGreen"/>
</Grid>
</Page>
我希望控件的用户能够用FrameworkElement
他想要使用的任何东西替换这些矩形。所以我需要一个ControlTemplate
.
但在 99% 的情况下,控件的用户对现有功能感到满意,所以我希望他能够说:
后面的代码:
mycontrol.Left.Fill = ....
XAML:
<mycontrol>
<mycontrol.Left.Fill = "Red"/>
</mycontrol>
这似乎是不可能的,因为如果我支持控件模板,我真的没有任何 UI 元素或 xaml。我只有文件后面的代码。我想我可以有一个DependencyProperty
Left
,但只要我没有某种容器来保存不会有多大好处的内容。我必须在文件后面的代码中创建网格。似乎不是一个好主意。
最后,我希望能够使用泛型,以便用户可以指定部件的类型:
MyControl mycontrol<TLeft, TRight> = new MyControl<Rectangle, Button>();
由于类型安全(无需FrameworkElement
转换为正确的类型),这将有助于代码背后的代码。不幸的是,我认为 XAML 方面并不真正支持泛型。
有没有解决这个问题的方法,还是真的“从 Control 继承以支持ControlTemplate
s 但失去控件的易用性。从 UserControl 继承以支持易用性但失去ControlTemplate
支持”?