Wpf 将ControlTemplate与用户控件混合使用是一个好主意吗?
用户控件(Wpf 将ControlTemplate与用户控件混合使用是一个好主意吗?,wpf,user-controls,controltemplate,Wpf,User Controls,Controltemplate,用户控件(public MyControl:UserControl)既支持ControlTemplate又支持现有内容,这是否可能也是一个好主意?我知道ControlTemplates只能在从控件继承时使用(public MyControl:Control),但我发现如果UserControl.xaml为空,也可以将它们与UserControl一起使用 假设我有一个控件,它有两个并排的矩形,如下所示: <Page xmlns="http://schemas.microsoft.com/wi
public MyControl:UserControl
)既支持ControlTemplate
又支持现有内容,这是否可能也是一个好主意?我知道ControlTemplate
s只能在从控件继承时使用(public MyControl:Control
),但我发现如果UserControl.xaml为空,也可以将它们与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>
XAML:
这将有助于代码隐藏,因为类型安全(无需将FrameworkElement
转换为正确的类型)。不幸的是,我认为XAML端并不真正支持泛型
此问题是否有解决方案,或者它是否真的“继承自控件以支持
ControlTemplate
s但失去控件的易用性。继承自UserControl以支持易用性但失去ControlTemplate
support”?向控件添加依赖项属性:
public static DependencyProperty LeftFillProperty = DependencyProperty.
Register("LeftFill", typeof(Brush), typeof(MyControl));
public Brush LeftFill
{
get { return (Brush)GetValue(LeftFillProperty); }
set { SetValue(LeftFillProperty,value); }
}
然后在默认控件模板中使用:
<Rectangle Name="left" Grid.Column="0" Height="90" Fill="{TemplateBinding LeftFill}"/>
或(XAML)
当您使用默认模板以及有人编写新控件模板时,他们有责任决定如何处理LeftFill属性(或者完全忽略它)
BTW,您应该考虑将名称从“左”和“右”改为“主面板”和“详细面板”、“FoldersArea”和“文件区域”,无论控件中的逻辑用法是什么,这将解决有人用一个模板替换默认模板的问题,该模板以不同的布局显示相同的数据。(例如,顶部和底部而不是左侧和右侧)
MyControl mycontrol<TLeft, TRight> = new MyControl<Rectangle, Button>();
public static DependencyProperty LeftFillProperty = DependencyProperty.
Register("LeftFill", typeof(Brush), typeof(MyControl));
public Brush LeftFill
{
get { return (Brush)GetValue(LeftFillProperty); }
set { SetValue(LeftFillProperty,value); }
}
<Rectangle Name="left" Grid.Column="0" Height="90" Fill="{TemplateBinding LeftFill}"/>
ctrl.LeftFill = Brushes.Red;
<c:MyControl LeftFill="Red"/>