我有9种不同的控件。他们都有背景。背景由图像,其他控件或两者组成。所有这些背景都有另一种背景。
将此视为带有幻灯片,幻灯片布局和幻灯片母版的Power Point - 按此顺序继承。我有9个幻灯片/控件。
现在,在每个控件中,我每次都会分别写出所有XAML。我认为必须有办法不在每个项目中写出这些。理想情况下,我想创建的是一组可以重用的XAML。
这是一些伪XAML:
<UserControl x:Name="Control1">
<MyBackground (ControlLayout1)/>
</UserControl>
<UserControl x:Name="Control2">
<MyBackground (ControlLayout2)/>
</UserControl>
<UserControl x:Name="Control3">
<MyBackground (ControlLayout3)/>
</UserControl>
然后 ControlLayouts 的某个地方(我不知道,像Application.Resources或其他地方)
<Canvas x:Name="ControlLayout1">
<MyMasterBackground (ControlMaster1)/>
</Canvas>
<Canvas x:Name="ControlLayout2">
<MyMasterBackground (ControlMaster1)/>
<TextBox Text="The Control 2">
</Canvas>
<Canvas x:Name="ControlLayout3">
<MyMasterBackground (ControlMaster2)/>
<TextBox Text="The Control 3">
</Canvas>
然后是 ControlMasters
<Canvas x:Name="ControlMaster1">
<Canvas.Background>
<ImageBrush ImageSource="/Images/image1.jpg" />
</Canvas.Background>
</Canvas>
<Canvas x:Name="ControlMaster2">
<Canvas.Background>
<ImageBrush ImageSource="/Images/image2.jpg" />
</Canvas.Background>
<TextBox Text="Control Master 1">
</Canvas>
一旦定义,ControlLayouts和ControlMaster就不需要改变 - 它们是静态的。
如果我可以将这些全部放在一个位置并重复使用XAML,那么除了拥有更小的XAP之外,我希望我的应用程序中的性能会得到改善,因为ControlLayouts会自动获得BitmapCached或类似的东西。
首先,是否有一个很好的策略来实现上述(ControlLayouts和Masters没有任何代码隐藏)?其次,在Control1,Control2等的加载中性能会有所提高吗?最后,如果它们是纯粹的用户控件(即它们背后有一些代码),那么性能会更好吗?
提前致谢!
答案 0 :(得分:1)
你要求的是几件事的组合:
关于Background背景:只需在UserControl后面的代码中创建一个类型为Brush的依赖属性(让我们称之为MyBackgroundDP),并将其绑定到您的XAML,如:
<UserControl ...>
<Grid Background={"Binding MyBackgroundDP, RelativeSource={RelativeSource Mode=FindAncestor, AncestoryType=UserControl}}">
<!-- More XAML declarations -->
</Grid>
</UserControl>
要创建依赖项属性,您可以使用visual studio中的内置代码段:propdp
只需编写“propdp”和TAB两次。填写字段,这一切都很好。
好吧,这很容易,对吧? ;)
现在更难的部分是:制作所谓的母版页
实际上它与背景的东西没什么不同。
声明另一个依赖项属性,仅此类型为object,或者是FrameworkElement(更好)。
然后在您的XAML中,您声明了一种占位符:ContentControl
。在这个例子中我们称之为MyContentDP:
<UserControl ...>
<Grid Background={"Binding MyBackgroundDP, RelativeSource={RelativeSource Mode=FindAncestor, AncestoryType=UserControl}}">
<ContentControl ContentTemplate="{Binding MyContentDP, RelativeSource={RelativeSource Mode=FindAncestor, AncestoryType=UserControl}}" />
</Grid>
</UserControl>
然后你可以在这个“主视图”中微调你想要提供的任何其他内容,在网格周围添加一个边框,放一些花,你可以命名。
一旦完成,这就是你如何使用它,假设它被称为MyUserControl
<Window ...
xmlns:local="...reference_to_your_usercontrol_dll/exe">
<Grid>
<local:MyUserControl MyBackgroundDP="Red">
<local:MyUserControl.MyContentDP>
<!-- More XAML declarations here -->
</local:MyUserControl.MyContentDP>
</local:MyUserControl>
</Grid>
</Window>
现在的表现点:
如果您将所有XAML作为自定义控件(来自UserControl的 DIFFERENT ),则可以将所有XAML放入App.xaml中
为什么?因为解析XAML可能是一个密集型操作,如果你让WP7 / SL在运行时随时解析它,你就会失去性能。
相反,你的App.xaml在启动时被解析,然后它在内存中。这就是加载应用程序时所做的。你可以获得性能提升,虽然对于少量XAML的控件来说它是最小的,但它仍然是一个很好的做法。
希望这有帮助,
巴布。