【问题标题】:Using UserControl as ResourceDictionary使用 UserControl 作为 ResourceDictionary
【发布时间】:2017-05-17 08:27:52
【问题描述】:

是否可以使用我在另一个 UserControl 中定义的资源,而无需为 ResourceDictionary 使用额外的文件。

我有一个用户控件“ViewCostumers”,并在其中定义了一个包含所有客户的 ListView 的 DataTemplate。 现在我编写了一个 UserCotnrol“ViewOverview”,其中应该出现相同的 ListView。如果可能的话,我想将 LsitView 保留在文件“ViewCostumer”中。

提前致谢

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

< ResourceDictionary> 
< ResourceDictionary.MergedDictionaries>         
< ResourceDictionary Source="View/ViewCostumer.xaml" /> 
< /ResourceDictionary.MergedDictionaries>
< /ResourceDictionary>

【问题讨论】:

  • 资源是通过它们的键来引用的,所以任何你想使用资源的地方只要把键放在你的代码中就可以了……你可以使用的次数没有限制相同的键。

标签: c# wpf xaml user-controls resourcedictionary


【解决方案1】:

是否可以使用我在另一个 UserControl 中定义的资源,而无需为 ResourceDictionary 使用额外的文件。

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

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

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

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

【讨论】:

    【解决方案2】:

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

    查看Creating and Consuming Resource Dictionaries in WPF and 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>
    

    【讨论】:

    • 这完全不是我想要的。我想将资源保留在原始文件中(这是一个用户控件)
    • 我理解您的问题的方式是您不想创建额外的文件。无论如何,这是一个选项,因为您的 Resources 的范围仅在放置它的用户控件上,因此无法共享。
    • 我真正希望工作的是我将 DataTempalte/ListView 保留在原始文件中。然后我想从另一个文件(如
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多