1

拥有同时支持s 和现有内容的用户控制 ( )是否可能并且是个好主意?我知道s 应该只在您从 Control ( ) 继承时使用,但我发现如果您的 UserControl.xaml 为空,您也可以使用它们。public MyControl: UserControlControlTemplateControlTemplatepublic MyControl: ControlUserControl

想象一下,我有一个控件,它有两个并排的矩形,如下所示:

<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 继承以支持ControlTemplates 但失去控件的易用性。从 UserControl 继承以支持易用性但失去ControlTemplate支持”?

4

1 回答 1

2

Add a dependency property to the control:

public static DependencyProperty LeftFillProperty = DependencyProperty.
   Register("LeftFill", typeof(Brush), typeof(MyControl));

public Brush LeftFill
{
   get { return (Brush)GetValue(LeftFillProperty); }
   set { SetValue(LeftFillProperty,value); }
}

Then in the default control template use:

<Rectangle Name="left" Grid.Column="0" Height="90" Fill="{TemplateBinding LeftFill}"/>

This will left you use (C#)

ctrl.LeftFill = Brushes.Red;

or (XAML)

<c:MyControl LeftFill="Red"/>

when you use the default template and when someone writes a new control template it's their responsibility to decide what to do with the LeftFill property (or to ignore it completely).

BTW, you should consider changing the names from "left" and "right" to something else ("MasterPanel" and "DetailPanel", "FoldersArea" and "FilesArea", whatever the logical usage in your control is), this will solve the issue of someone replacing the default template with a template that displays the same data in a different layout (top and bottom instead of left and right for example).

于 2009-02-08T11:01:16.073 回答