如何创建仅存在于 ResourceDictionary 上下文中的样式
如何创建仅存在于 ResourceDictionary 上下文中但不存在于包含该 ResourceDictionary 的控件上下文中的样式?
例如,我希望能够有一个如下所示的 ResourceDictionary:
<!-- ControlTemplates.xaml -->
<ResourceDictionary>
<!-- Private Local styles used to set up the publicly usable templates -->
<Style x:Key="TextBoxes" TargetType="TextBox">
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
<!-- End of Private Local Stuff -->
<!-- Public Dictionary Resources Follow -->
<ControlTemplate x:Key="CustomTextBox">
<TextBox Style="{StaticResource TextBoxes}" />
</ControlTemplate>
</ResourceDictionary>
然后在其他一些控件或窗口中,我希望能够:
<Window>
<Window.Resources>
<ResourceDictionary Source="ControlTemplates.xaml">
</Window.Resources>
<Grid>
<!-- This Should Work -->
<CustomControl Template="{StaticResources CustomTextBox}">
<!-- This Should NOT Work! -->
<TextBox Template="{StaticResources TextBoxes}">
</Grid>
</Window>
How can I create a style that only exists within the context of a ResourceDictionary, but not in the context of controls that include that ResourceDictionary?
For instance, I want to be able to have a ResourceDictionary that looks like this:
<!-- ControlTemplates.xaml -->
<ResourceDictionary>
<!-- Private Local styles used to set up the publicly usable templates -->
<Style x:Key="TextBoxes" TargetType="TextBox">
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
<!-- End of Private Local Stuff -->
<!-- Public Dictionary Resources Follow -->
<ControlTemplate x:Key="CustomTextBox">
<TextBox Style="{StaticResource TextBoxes}" />
</ControlTemplate>
</ResourceDictionary>
And then in some other control or window, I want to be able to go:
<Window>
<Window.Resources>
<ResourceDictionary Source="ControlTemplates.xaml">
</Window.Resources>
<Grid>
<!-- This Should Work -->
<CustomControl Template="{StaticResources CustomTextBox}">
<!-- This Should NOT Work! -->
<TextBox Template="{StaticResources TextBoxes}">
</Grid>
</Window>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
非常接近您要查找的内容的一种方法是将“私有”样式从
ControlTemplates.xaml
移动到它们自己的ResourceDictionary
中,然后从在 ControlTemplates.xaml 的控件模板中:ControlTemplates.xaml:
ControlTemplatePrivateStyles.xaml:
那么窗口的 xaml 看起来像这样:
这样您就不能使用“私有”样式除非您明确引用该资源字典。仅通过引用 ControlTemplates.xaml 资源字典无法访问它们。
One way to get quite close to what you are looking for is to move the "private" styles from
ControlTemplates.xaml
into their ownResourceDictionary
, and then reference that resource dictionary from within the control templates in ControlTemplates.xaml:ControlTemplates.xaml:
ControlTemplatePrivateStyles.xaml:
Then the xaml for the window would look like this:
This way you could not use the "private" styles unless you explicitly reference that resource dictionary. They will not be accessible by just referncing the ControlTemplates.xaml resource dictionary.