【发布时间】:2021-06-04 08:33:12
【问题描述】:
我正在尝试在我的软件中实现 MVVM。
我想要什么:我想要一个 ViewModel.cs (ViewModel) 文件来代替 MainWindow.xaml.cs (MainWindow) 文件(里面应该只有 InitializeComponent())
我做了什么:我将数据从我的 MainWindow 移动到新创建的 ViewModel。
出了什么问题:我在将 MainWindow 的 XAML 文件绑定到 ViewModel 时遇到问题,出现错误
当前上下文中不存在名称“comPortList/donglesView”
我参考了我认为与我的问题相关的以下链接
但我一无所获。有什么我想念的吗?如果我没有提供足够的信息,请告知,或者让我知道。
有用的数据
- 相关 MainWindow.xaml 代码:底部三行(comPortList、btnPortOpen 和 donglesView)需要处理 ViewModel 中的代码。
<Window x:Class="comPortTesterEX.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:comPortTesterEX"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<!-- -->
<Grid>
<ListBox x:Name="comPortList" SelectionMode="Single" Grid.Row="0" Grid.Column="0" />
<Button x:Name="btnPortOpen" Grid.Row="0" Grid.Column="1" Click="PortOpen_Click" Content ="Open Port"/>
<TreeView x:Name="donglesView" Grid.Row="1" Grid.RowSpan="3" Grid.Column="0" Grid.ColumnSpan="2">
- ViewModel代码:1中最下面的三行代码,这里依赖代码,但是不知道怎么把两者联系起来。
namespace comPortTesterEX
{
class ViewModel : ObservableObject
{
public ObservableCollection<Dongle> dongles;
DispatcherTimer timer;
public ViewModel()
{
timer = new DispatcherTimer();
timer.Tick += new EventHandler(checkAndUpdateComPortList);
timer.Interval = new TimeSpan(0, 0, 1);
timer.Start();
dongles = new ObservableCollection<Dongle>();
Trace.WriteLine("Started");
donglesView.ItemsSource = dongles;
}
private void checkAndUpdateComPortList(object sender, EventArgs e)
{
List<String> portNames = new List<String>();
foreach (string portName in SerialPort.GetPortNames())
{
portNames.Add(portName);
}
if (SerialPort.GetPortNames().Count() == 0)
{
portNames.Clear();
}
comPortList.ItemsSource = portNames;
}
...
private void PortOpen_Click(object sender, RoutedEventArgs e)
{
bool isComPortInList = false;
//Checks for each highlighted item (limited to one)
foreach (String name in comPortList.SelectedItems)
{
if (dongles.Count() == 0) // If there is nothing in bottom list -> CREATE ONE
{
createDongle(dongles, name, 0);
}
else //If there is already a list
{
for (int i = 0; i < dongles.Count(); i++) // Compare highlighted to EVERY ITEM IN LIST
{
// Check if it already exists in list
if (dongles[i].ComPortName == name)
{
isComPortInList = true;
} // return true if it does
}
if (isComPortInList == false)
{
//Added element is last element, not 0th
createDongle(dongles, name, dongles.Count - 1);
}
}
}
}
}
}
ObservableObject 编码复制自 Rachel Lim 的 MVVM 页面,链接为 https://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/
【问题讨论】: