所以,我创建了一个基于XAML基础的子类(见下文),但是我在另一个项目中创建了子类,Visual Studio在TreeView上给出了一个错误,说“名称”ViewTree“不存在于目前的背景“。但是,存在于同一项目内的其他子类没有相同的错误。这是为什么?
我添加了对其他项目的引用,并使用了相同的命名空间,但仍然没有快乐。
谢谢!
基础XAML:
<UserControl x:Class="myLibrary.Material.ViewTreeSpace.ViewingTree"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Background="#00000000" >
<DockPanel>
<TreeView Name="ViewTree" />
</DockPanel>
</UserControl>
父代码隐藏:
namespace myLibrary.Material.ViewTreeSpace {
public partial class ViewingTree : Usercontrol {
public string TreeName = String.Empty;
public ViewingTree(){ }
}
不同项目中的子类:
namespace myLibrary.Material.ViewTreeSpace {
public class ImportedTree : ViewingTree {
public ImportedTree() : base() {
ViewTree.Items.Clear(); // <- This line gives me error
TreeName = "My imported Tree in another project."; // <- This works
}
}
编辑:我也注意到代码隐藏中存在的变量可以被引用,只有来自的UIElements不能。
编辑:收到@Liju答案后,我将TreeView设置为使用x:FieldModifier="public"
。但是,我现在得到以下错误。
System.Exception: The component 'myLibrary.Material.ViewTreeSpace.ImportedTree' does not have a resource identified by the URI '/myLibrary;component/material/view%20tree/viewingtree.xaml'.
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at myLibrary.Material.ViewTreeSpace.ViewingTree.InitializeComponent()
at myLibrary.Material.ViewTreeSpace.ViewingTree..ctor()
at myLibrary.Material.ViewTreeSpace.ImportedTree..ctor() in c:\..\ImportedTree.cs:line 51
根据我的发现,不可能从不同的程序集继承XAML类。 (即Answer for "The component does not have a resource identified by the URI显然,这是一个problem since 2008。
编辑2:
使用@ Liju的第二个答案,我尝试设置ResourceDictionary,但它说它无法加载资源。
System.InvalidOperationException: ResourceDictionary LoadFrom operation failed with URI 'pack://application:,,,/myLibrary;component/Material/View Tree/ViewingTree.xaml'.
at System.Windows.ResourceDictionary.set_Source(Uri value)
at myLibrary.Material.ViewTreeSpace.ImportedTree..ctor() in c:\..\ImportedTree.cs:line 59
答案 0 :(得分:1)
您可以将x:FieldModifier属性用作Public X:FieldModifier = “公共”
默认的fieldmodifier值为'not public'。
http://msdn.microsoft.com/en-us/library/vstudio/aa970905(v=vs.90).aspx
答案 1 :(得分:1)
我假设您在运行时收到此错误。如果那时,在派生的构造函数中明确加载treeview资源 示例代码:
ResourceDictionary treeResource = new ResourceDictionary
{
Source = new Uri(@"pack://application:,,,/<<AssemblyName>>;component/<<Path to the xaml to load>>")
};
this.Resources.MergedDictionaries.Add(treeResource);
希望这有帮助!