How to make a Style that only exists within the context of a ResourceDictionary

前端 未结 1 1099
终归单人心
终归单人心 2021-01-13 11:47

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 in

相关标签:
1条回答
  • 2021-01-13 12:27

    One way to get quite close to what you are looking for is to move the "private" styles from ControlTemplates.xaml into their own ResourceDictionary, and then reference that resource dictionary from within the control templates in ControlTemplates.xaml:

    ControlTemplates.xaml:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <!-- By referencing the ResourceDictionary from within the ControlTemplate's
             resources it will only be available for the ControlTemplate and not for those
             who reference ControlTemplates.xaml -->
        <ControlTemplate x:Key="CustomTextBox">
            <ControlTemplate.Resources>
                <ResourceDictionary Source="ControlTemplatePrivateStyles.xaml" />
            </ControlTemplate.Resources>
    
            <TextBox Style="{StaticResource TextBoxes}" Text="Some text" />
        </ControlTemplate>
    
    </ResourceDictionary>
    

    ControlTemplatePrivateStyles.xaml:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <Style x:Key="TextBoxes" TargetType="TextBox">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    
    </ResourceDictionary>
    

    Then the xaml for the window would look like this:

    <Window x:Class="ResourceDictionaryPrivateStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ResourceDictionaryPrivateStyle="clr-namespace:ResourceDictionaryPrivateStyle"
        Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <ResourceDictionary Source="ControlTemplates.xaml" />
        </Window.Resources>
    
        <StackPanel>
            <!-- This works -->
            <ResourceDictionaryPrivateStyle:CustomControl Template="{StaticResource CustomTextBox}" />
    
            <!-- This does not work, unless you explicitly reference ControlTemplatesPrivateStyles.xaml here in the window-->
            <TextBox Text="Text" Style="{StaticResource TextBoxes}" />
        </StackPanel>
    </Window>
    

    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.

    0 讨论(0)
提交回复
热议问题