使用 UserControl 作为资源字典

问题描述 投票:0回答:2

是否可以在另一个 UserControl 中使用我在

<UserControl.Resources>
中定义的资源,而不使用 ResourceDictionary 的额外文件。

我有一个用户控件“ViewCostumers”,在

<UserControl.Resources>
中我定义了一个带有所有客户的ListView的DataTemplate。 现在我编写一个用户控件“ViewOverview”,其中将出现相同的ListView。如果可能的话,我想将 ListView 保留在文件“ViewCostumer”中。

提前致谢

编辑: 我试图做的是将 DataTempalte/ListView 保留在原始文件中。然后我想从另一个文件(如资源字典,只有 ViewCostumer 是 UserControl)引用该文件(这是 UserControl):

< ResourceDictionary> 
< ResourceDictionary.MergedDictionaries>         
< ResourceDictionary Source="View/ViewCostumer.xaml" /> 
< /ResourceDictionary.MergedDictionaries>
< /ResourceDictionary>
c# wpf xaml user-controls resourcedictionary
2个回答
1
投票

是否可以使用我在另一个用户控件中定义的资源,而不使用资源字典的额外文件。

不,不是。毕竟,这正是 ResourceDictionaries 的用途。

我想将资源保留在原始文件(这是一个用户控件)中。

如果您打算使用除此特定

UserControl
以外的任何其他控件中的资源,您不能也不应该这样做。如果您打算在任何其他控件中使用此资源,那么在
UserControl
中定义资源根本没有意义。

您应该做的是在

ResourceDictionary
中定义公共资源,然后按照@Ephraim的建议将其合并到两个控件中。


0
投票

您可以将资源移至应用程序范围。

查看在 WPF 和 Silverlight 中创建和使用资源字典,特别是将资源移至应用程序范围

这个想法是将资源移动到 Application.xaml 中,以便可以在整个应用程序中使用。

Application.xaml

<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="ResourceDictionaryDemo.App"
    xmlns:my="clr-namespace:System;assembly=mscorlib">
    <Application.Resources>
        <LinearGradientBrush x:Key="formBackground" EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="Blue" Offset="0" />
            <GradientStop Color="#460000FF" Offset="1" />
        </LinearGradientBrush>
        <my:String x:Key="applicationTitle">Resource Dictionary Demo</my:String>
        <my:Double x:Key="applicationTitleFontSize">18</my:Double>
        <SolidColorBrush x:Key="applicationTitleForeground">Yellow</SolidColorBrush>
    </Application.Resources>
</Application>
© www.soinside.com 2019 - 2024. All rights reserved.