gpt4 book ai didi

c# - 将 DataContext 窗口绑定(bind)到 ViewModel

转载 作者:行者123 更新时间:2023-12-03 11:03:26 25 4
gpt4 key购买 nike

好的,我尝试了几种方法,但都没有像我的情况那样奏效。我有一个带有单个 ComboBox 的简单窗口。我正在将代码更改为 MVVM,所以现在一切都在代码隐藏中,应该转到 ViewModel 等。
但即使在第一步(将 ViewModel 绑定(bind)到 View /窗口),我似乎也无法将它们绑定(bind)在一起。
我的窗口 XAML:

<Window x:Class="CustomerGuidance.ClientWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VM="clr-namespace:CustomerGuidance.ViewModels"
Title="Stop'n'Go - Client" Height="22" Width="229"
Loaded="ClientWindow_OnLoaded" WindowStyle="None"
WindowStartupLocation="Manual" Top="0" Left="0"
ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True">
<Window.DataContext>
<VM:EmployeeViewModel />
</Window.DataContext>
<Canvas Background="Gainsboro">
<ComboBox Name="EmployeesComboBox"
ItemsSource="{Binding EmployeeEntries}"
Width="192" FontFamily="Arial" FontSize="14">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Lastname}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding Surname}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Canvas>

ViewModel 看起来像这样:
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace CustomerGuidance.ViewModels
{
public class EmployeeViewModel : INotifyPropertyChanged
{
public EmployeeViewModel()
{
}

public static ObservableCollection<ServerWindow.EmployeeEntry> EmployeeEntries { get; set; } = new ObservableCollection<ServerWindow.EmployeeEntry>();

private string _surname;
private string _lastname;
private int _id;

public string Surname
{
get { return _surname; }
set
{
if (_surname == value)
return;
_surname = value;
NotifyPropertyChanged("Surname");
}
}

public string Lastname
{
get { return _lastname; }
set
{
if (_lastname == value)
return;
_lastname = value;
NotifyPropertyChanged("Lastname");
}
}

public int Id
{
get { return _id; }
set
{
if (_id == value)
return;
_id = value;
NotifyPropertyChanged("Id");
}
}

public virtual event PropertyChangedEventHandler PropertyChanged;

protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

我收到以下错误消息:“名称“EmployeeViewModel”在命名空间“clr-namespace:CustomerGuidance.ViewModels”中不可用。现在的问题是:我缺少什么?如何将 ViewModel 绑定(bind)到我的 window-XAML ?

最佳答案

您应该构建代码以使错误消失。
这是因为命名空间在设计者依赖的程序集中(您的程序)在构建之前尚不可用。

关于c# - 将 DataContext 窗口绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43782287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com