【问题标题】:Setting Window.Datacontext设置 Window.Datacontext
【发布时间】:2019-01-29 01:41:15
【问题描述】:

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

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>

【问题讨论】:

    标签: wpf xaml data-binding


    【解决方案1】:

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

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

    MyViewModel 可以是你想绑定的任何东西。

    【讨论】:

      【解决方案2】:

      定义类

       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>
      

      它应该可以工作。

      【讨论】:

        【解决方案3】:

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

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

        <Window.DataContext>
            <ViewModel/>
        </Window.DataContext>
        

        【讨论】:

          猜你喜欢
          • 2012-06-18
          • 1970-01-01
          • 2019-04-21
          • 1970-01-01
          • 2016-07-31
          • 1970-01-01
          • 1970-01-01
          • 2015-04-21
          • 2015-04-02
          相关资源
          最近更新 更多