【问题标题】:Why can you inherit a class over project boundaries, but not its attached XAML?为什么可以跨项目边界继承一个类,但不能继承其附加的 XAML?
【发布时间】:2009-09-30 15:03:01
【问题描述】:

(这个问题是对my other question on this topic 的改进,有点复杂,但我真的很想了解为什么这不起作用,所以这里有一个更直接的例子

我想做什么:在一个项目中创建一个简单的类(无 XAML),该类继承另一个项目中的 WPF UserControl(使用 XAML)。

这是我在主项目中的继承类:

EmployeeEditor.cs:

using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using CoreApp;

namespace TestInheritUserControl234
{
    class EmployeeEditor : BaseEditor
    {
        public EmployeeEditor()
        {
            TextBlock tb = new TextBlock();
            tb.Text = "This was added in EmployeeEditor";
            tb.Foreground = new SolidColorBrush(Colors.Blue);
            EditorContent.Children.Add(tb);
        }
    }
}

这是我在第二个项目中的基类,请注意它有 x:Name="EditorContent":

BaseEditor.xaml:

<UserControl x:Class="CoreApp.BaseEditor"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel x:Name="EditorContent" Margin="5">
        <TextBlock x:Name="TheMessage" Text="This was added in BaseEditor XAML."/>
    </StackPanel>
</UserControl>

BaseEditor.xaml.cs:

using System.Windows.Controls;
namespace CoreApp
{
    public partial class BaseEditor : UserControl
    {
        public BaseEditor()
        {
            InitializeComponent();

            TextBlock tb = new TextBlock();
            tb.Text = "This was added in BaseEditor code-behind.";
            EditorContent.Children.Add(tb);
        }
    }
}

问题是当它运行时,我收到错误名称“EditorContent”在当前上下文中不存在

但是,如果所有类都在一个项目中,它运行良好。

为什么您可以跨项目边界继承一个类,但不能继承其附加的 XAML?

【问题讨论】:

    标签: c# wpf xaml inheritance user-controls


    【解决方案1】:

    如果我没记错的话,默认保护级别是内部的,这就是这种情况下的问题。要修复它,请按如下方式更改 StackPanel 声明:

    <StackPanel x:Name="EditorContent" x:FieldModifier="public" Margin="5">
    

    更新:这确实带来了另一个问题,这似乎是 WPF 的一个限制:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/4f6385ea-a176-489e-9f13-0c812195e323 Microsoft 出于某种原因专门阻止从另一个程序集继承 XAML 定义的类。引用 System.Windows.Application.LoadComponent():

    if ((info2 == null) || (info2.Assembly != component.GetType().Assembly))
    {
        throw new Exception(SR.Get("UriNotMatchWithRootType", new object[] { component.GetType(), resourceLocator }));
    }
    

    【讨论】:

    • 如果我这样做,它会告诉我:“组件“TestInheritUserControl234.CustomerEditor”没有可以由“/CoreApp;component/baseeditor.xaml”识别的资源。(原文:“ Die Komponente "TestInheritUserControl234.CustomerEditor" verfügt nicht über eine Ressource, die vom URI "/CoreApp;component/baseeditor.xaml" identifiziert wird.")
    • 啊,这就是新的WPF CrystalReportsViewer不能被继承的原因吧。
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多