2

我正在尝试将我的视图模型用作窗口的数据上下文,但出现错误:

Windows Presentation Foundation (WPF) 项目不支持 ViewModel。

显然,我不了解有关我的窗口到我的视图模型的语法和数据绑定的某些内容,但我不确定我不知道的是什么。

关于我应该阅读什么的任何建议?

<Window x:Class="SunnyBeam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SunnyBeam" Height="488.358" Width="1014.552">
    <Window.DataContext>
        <ViewModel/>
    </Window.DataContext>
    <Grid>

    </Grid>
</Window>
4

3 回答 3

1

通常我通过这样的代码隐藏设置 DataContext :

public partial class Flor1 : Window
{
    public Flor1()
    {
        var dc = new MyViewModel();
        dc.LoadData();
        DataContext = dc;
        InitializeComponent();
    }
}

代替 MyViewModel 可能是您想要绑定的任何东西。

于 2012-11-16T04:10:45.553 回答
1

定义类

 public class ViewModel
 {
    public string Name { get; set; }
    public ViewModel()
    {

    }
 }

在 xaml 中使用它

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <ui:ViewModel/>
</Window.DataContext>
<Grid>

</Grid>

它应该工作。

于 2012-11-16T04:11:51.793 回答
0

我想我会抛出这个错误的经验。

我的数据上下文设置与下面相同,并且不断收到 ViewModel 不存在的错误,我知道它确实存在。我拒绝在后面的代码中设置它,只是重建我的项目实际上修复了这个错误。

<Window.DataContext>
    <ViewModel/>
</Window.DataContext>
于 2019-01-28T17:41:15.383 回答