我想听听一些有关资源和UserControls
...
我意识到UserControls
有时具有我想要配置的属性-但在全局范围上并且不是按实例。
让我给你举个例子:
我实现了一个UserControl
,基本上代表一个制表符(我称为RibbonTab
):
每个标签都有自己的图标和文本(以及其他一些属性),它们都是DependencyProperties
,因此我可以像这样实例化我的标签:
<!-- Time Tracking Tab -->
<UserControls:RibbonTab
Icon="{StaticResource TimeTrackingTabIcon}"
Text="{StaticResource TimeTrackingTabHeaderString}"
LabelMode="AutoResize" ResizePriority="0"
Command="{Binding LoadTimeTrackingViewModelCommand}"/>
<!-- Vacation Tab -->
<UserControls:RibbonTab
Icon="{StaticResource VacationTabIcon}"
Text="{StaticResource VacationTabHeaderString}"
LabelMode="AutoResize" ResizePriority="1"
Command="{Binding LoadVacationViewModelCommand}"/>
<!-- Payout Tab -->
<UserControls:RibbonTab
Icon="{StaticResource PayoutTabIcon}"
Text="{StaticResource PayoutTabHeaderString}"
LabelMode="AutoResize" ResizePriority="2"
Command="{Binding LoadPayoutViewModelCommand}"/>
如您所见,所选标签的背景颜色为白色。当前是ControlTemplate
中的固定值。我希望它是可配置的。
我想出了各种可能的解决方案,但是我不确定是否思考过多:
1。)使用DependencyProperty
我可以引入另一个DependencyProperty
之类的"SelectedTabColor"
并实例化这些标签:
<!-- Time Tracking Tab -->
<UserControls:RibbonTab
<!-- All of the previous properties go here... -->
SelectedTabColor="White"/>
<!-- Vacation Tab -->
<UserControls:RibbonTab
<!-- All of the previous properties go here... -->
SelectedTabColor="White"/>
<!-- Payout Tab -->
<UserControls:RibbonTab
<!-- All of the previous properties go here... -->
SelectedTabColor="White"/>
很容易看出该技术需要一遍又一遍地附加值,但您实际上只想(全局)设置一次此属性即可完成。
2。)使用ResourceDictionary
我可以使我的UserControl
从应用程序的StaticResource
引用ResourceDictionary
:
<UserControl x:Class="MyApp.View.UserControls.RibbonTab">
<Grid>
<!-- Lots of stuff omitted here... -->
<Rectangle Fill="{StaticResource RibbonTab_SelectedTabColor}"/>
<!-- More stuff omitted here... -->
</Grid>
</UserControl>
但是,我的UserControl
要求应用程序/集成具有一个StaticResource
,其命名与此完全相同。将UserControl
移植到另一个项目将是一场噩梦...
3。)使用UserControl.Resources + StaticResources
另一种可能性是利用Resources
的{{1}}属性并将其所需的定义直接放置为UserControl
:
StaticResources
这很不错,因为每个<UserControl x:Class="MyApp.View.UserControls.RibbonTab">
<UserControl.Resources>
<!--#region Configurable properties -->
<Color x:Key="SelectedTabColor">White</Color>
<!--#endregion Configurable properties -->
</UserControl.Resources>
<Grid>
<!-- Lots of stuff omitted here... -->
<Rectangle Fill="{StaticResource SelectedTabColor}"/>
<!-- More stuff omitted here... -->
</Grid>
</UserControl>
与实际使用它的元素一起存储,而不是拥有很大的StaticResource
并丢失了在哪里使用的跟踪。
但是,缺点是您无法跨多个ResourceDictionary
重用通用定义(例如,应用程序在其ResourceDictionary
中定义了某种强调色),但必须在各处重新定义它,这很难维护。
4。)使用UserControl.Resources + ResourceKeys
到目前为止,我能想到的最好的方法是在UserControls
的{{1}}中用StaticResources
(而不是实际值)定义ResourceKeys
。集成商必须将Resources
设置为应用程序的现有资源:
UserControl
我尚未对此进行详细评估。我现在看到的唯一缺点是,仅在运行时而不是在设计时检查引用资源的类型。
我想念明显的东西...吗?是否有解决此问题的优雅方法?很高兴听到一些意见,因为到目前为止我对如何进行操作还不确定...