programing

WPF 사용자 제어에서 Import된 리소스와 로컬 리소스를 결합하는 방법

showcode 2023. 4. 15. 09:41
반응형

WPF 사용자 제어에서 Import된 리소스와 로컬 리소스를 결합하는 방법

공유 리소스와 개별 리소스를 모두 필요로 하는 여러 WPF 사용자 컨트롤을 쓰고 있습니다.

다른 리소스 파일에서 리소스를 로드하기 위한 구문을 알아냈습니다.

<UserControl.Resources>
    <ResourceDictionary Source="ViewResources.xaml" />
</UserControl.Resources>

그러나 이렇게 하면 다음과 같은 리소스를 로컬로 추가할 수도 없습니다.

<UserControl.Resources>
    <ResourceDictionary Source="ViewResources.xaml" />
    <!-- Doesn't work: -->
    <ControlTemplate x:Key="validationTemplate">
        ...
    </ControlTemplate>
    <style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
        ...
    </style>
    ...
</UserControl.Resources>

Resource Dictionary를 찾아봤습니다.MergedDictionary는 둘 이상의 외부 사전만 병합할 수 있으며 추가 리소스를 로컬로 정의할 수는 없습니다.

내가 뭔가 사소한 걸 놓치고 있는 게 틀림없어?

다음 사항을 언급해야 합니다.저는 WinForms 프로젝트에서 사용자 컨트롤을 호스팅하고 있기 때문에 App.xaml에 공유 리소스를 넣는 것은 선택사항이 아닙니다.

난 이해했다.솔루션에는 Merge Dictionary가 포함되어 있지만, 다음과 같이 구체적인 내용이 적절해야 합니다.

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ViewResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- This works: -->
        <ControlTemplate x:Key="validationTemplate">
            ...
        </ControlTemplate>
        <style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
            ...
        </style>
        ...
    </ResourceDictionary>
</UserControl.Resources>

즉, 로컬리소스는 ResourceDictionary 태그 내에 네스트되어 있어야 합니다.는 틀렸습니다.

MergeDictionaries 섹션 내에서 로컬리소스를 정의할 수 있습니다.

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- import resources from external files -->
            <ResourceDictionary Source="ViewResources.xaml" />

            <ResourceDictionary>
                <!-- put local resources here -->
                <Style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
                    ...
                </Style>
                ...
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

MergeDictionary를 사용합니다.

나는 여기서 다음과 같은 예를 들었다.

파일 1

<ResourceDictionary 
  xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation "
  xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml " > 
  <Style TargetType="{x:Type TextBlock}" x:Key="TextStyle">
    <Setter Property="FontFamily" Value="Lucida Sans" />
    <Setter Property="FontSize" Value="22" />
    <Setter Property="Foreground" Value="#58290A" />
  </Style>
</ResourceDictionary>

파일 2

   <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="TextStyle.xaml" />
        </ResourceDictionary.MergedDictionaries>
      </ResourceDictionary> 

언급URL : https://stackoverflow.com/questions/1333786/how-to-combine-imported-and-local-resources-in-wpf-user-control

반응형