【发布时间】:2020-07-09 00:41:50
【问题描述】:
我有我想在 TabControl 的不同选项卡中的几个 ComboBox 控件中使用的字符串列表。字符串列表位于公共 ObservableCollection 中。问题是,我无法在 XAML 文件的
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace APX_Interface
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<String> MyStringList; // not initialized yet
public class NameList : ObservableCollection<String>
{
public NameList() : base()
{
Add("Willam");
Add("Isak");
Add("Victor");
Add("Jules");
}
}
}
}
这是 XAML:
Window x:Class="APX_Interface.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:APX_Interface"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:MyStringList x:Key="Strings"/>
<local:NameList x:Key="Names"/>
</Window.Resources>
<Grid>
</Grid>
当我输入 local: 时,唯一显示为自动完成的是 App。编译代码我得到几个这样的错误:
错误 XML 命名空间“clr-namespace:APX_Interface”中不存在标记“MyStringList”。
错误 XDG0008 名称“MyStringList”在命名空间“clr-namespace:APX_Interface”中不存在。
错误 XLS0414 找不到类型“local:MyStringList”。确认您没有丢失程序集引用并且所有引用的程序集都已构建。 类 NameList 的相同错误
在查看了许多示例以及此处的其他讨论后,我无法确定我缺少什么。
感谢所有建议,很遗憾我们还没有解决这个问题。 我在这里发布了带有建议更改的代码和我的 cmets:
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace APX_Interface
{
public class NameList : ObservableCollection<String>
// This class is now THE ONLY thing visible in <Window.Resources>
// but not any instance of the class.
{
public NameList() : base()
{
}
}
public partial class MainWindow : Window
{
// This instance of the class is NOT visible in <Window.Resources> ???
public NameList MyNames { get { return _names;} }
// nor is this
public ObservableCollection<String> MyNumbers { get { return _numbers; } }
// nope
public NameList _names = null;
//Neither this one
public ObservableCollection<String> _numbers = null;
public MainWindow()
{
InitializeComponent();
// this doesn't make any difference
DataContext = this;
_names = new NameList();
_names.Add("fellow"); // populate dynamically
var _nr = new string[] // static strings
{
"One",
"Two",
"etc.",
};
_numbers = new ObservableCollection<string>(_nr);
}
}
}
【问题讨论】:
-
MyStringList 是您的公共字段。在资源中,您只能定义一个实例类型。口头描述你想要实现的东西。因为我无法从您的代码中理解这一点。
-
> 将 MyStringList 转换为属性。 – @neelesh bodgal 它不会解决任何问题。由于 Guillermo 不需要绑定,而是资源中的实例。
-
您可以使用 usercontrol 或 customcontrol 创建您想要的控件,以便在您的应用程序中任何需要的地方通用
-
让我更具体地解释一下这个问题。字符串列表是动态生成的(系统中可用的 COM 端口),其他列表是静态的(COM 参数),几个 ComboBox 控件必须在不同的选项卡中呈现这些列表。我现在正在做的是开始在 String[] 数组中加载端口列表并以编程方式设置项目来源,如下所示: DRCPort.ItemsSource = SerialPortsList;等等。这工作正常,但我想把它变成一个可绑定的列表。