C#WPF MVVM,获取两个主要对象实例

时间:2017-07-24 13:20:23

标签: c# wpf xaml mvvm

我是WPF和MVVM的新手,我正在尝试将属性链接到WPF表单上的文本框。但是,我似乎得到了主对象的两个实例,这导致-1退出错误。我认为这是由XAML文件中的类和DataContext依赖项引起的。

有人能指出我为什么会这样做的正确方向吗?

我的XAML的主要部分包括:

<Window 
    x:Class="MyProg.MainWindowViewModel"
    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:MyProg"
    xmlns:vm="clr-namespace:MyProg"
    mc:Ignorable="d"
    Title="MainWindow" Height="572" Width="855" WindowStartupLocation="CenterScreen" >

    <Window.Resources>
            <vm:MainWindowViewModel x:Key="viewModel" />
    </Window.Resources>

    <Grid DataContext="{StaticResource ResourceKey=viewModel}">
            <TextBox x:Name="textBox" 
                Text="{Binding FormTextBox}" />
    </Grid>
</Window>

我的模特包括:

namespace MyProg
{
    public class MyProgModel : INotifyPropertyChanged
    {
        private string _textBox;     // holds contents of text box

        public string MyTextBox
        {
            get { return _textBox; }

            set
            {
                _textBox = value;
                Console.WriteLine(_textBox);
                OnPropertyChanged("MyTextBox");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            Console.WriteLine("Keyboard Model OnPropertyChanged {0}", propertyName);

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

和查看模型:

namespace MyProg
{
    public partial class MyProg : Window,  INotifyPropertyChanged
    {
        private MyProgModel _mainWindowModel;

        private string _textBox = "Pan Galactic Gargle Blaster"; // holds contents of text box

        public MainWindowViewModel()
        {
            _mainWindowModel = new MyProgModel
            { // Instantiate and initialise _mainWindowModel
                MyTextBox = "Hello from me"
            };
        }

        public string FormTextBox
        {
            get { return _textBox; }

            set
            {
                _textBox = value;
                OnPropertyChanged("FormTextBox");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            Console.WriteLine("View model OnPropertyChanged {0}", propertyName);

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的viewmodel同时是一个视图 - 将它们分开,否则您在窗口资源中有一个可逆调用(DataContext需要)