我正在使用在Visual Studio中使用WPF的简单MVVM应用程序。我在这里提供View代码以及Model类。我唯一担心的是第一个Textbox没有与Form类的Name属性绑定。您可以跳过剩余的代码。我是MVVM体系结构和WPF的初学者。如果您认为合适,也可以建议我一些错误。
谢谢。
UI.xaml
<Window x:Class="MVVM.Views.UI"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:MVVM.ViewModels"
Title="UI" Height="300" Width="300">
<Grid>
<TextBox TextWrapping="Wrap" Text="{Binding MVVM.Models.Form.Name}" Margin="20,15,160,225" />
<TextBox TextWrapping="Wrap" Text="Back Color" Margin="20,73,195,167" />
<TextBox TextWrapping="Wrap" Text="Font Color" Margin="20,122,195,118"/>
<ListBox Name="listBox" ItemsSource="{Binding notifyChangedList}" HorizontalAlignment="Left" Margin="156,42,0,143" Height="85" Width="93" />
<Button Content="Finish" HorizontalAlignment="Left" Margin="112,163,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
Form.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace MVVM.Models
{
public class Form : INotifyPropertyChanged
{
public Form()
{
}
#region Variables
private String _name;
public String Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
private String _colorBack;
public String ColorBack
{
get { return _colorBack; }
set
{
_colorBack = value;
OnPropertyChanged("ColorBlack");
}
}
private String _colorFont;
public String Color_Font
{
get { return _colorFont; }
set
{
_colorFont = value;
OnPropertyChanged("ColorFont");
}
}
#endregion
#region INotifyPropertyChangedMembers
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
UI.xaml.cs
using MVVM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace MVVM.Views
{
public partial class UI : Window
{
public UI()
{
InitializeComponent();
DataContext = new Form();
}
}
}
我怀疑您错过了在UI.xaml.cs中初始化DataContext属性的过程。
尝试在构造函数中对其进行初始化
public UI()
{
this.DataContext = new MVVM.Models.Form();
}
在您的UI.xaml中,只需将文本与Name属性绑定
<TextBox TextWrapping="Wrap" Text="{Binding Name}" Margin="20,15,160,225" />
更新:[添加描述]
DataContext就像带有UI元素的“待绑定对象”的容器一样,一旦分配给任何UI元素,该UI元素的所有子代也将(种类)引用该绑定对象。因此,在本例中,为this.DataContext分配一个对象“ Form”就是说UI Window这是您要绑定的对象,因此所有UI子UI元素都将对此绑定对象进行引用。因此,当我们说Text =“ {Binding Name}”时,它已经知道绑定对象是Form,并且必须在该对象内查找Name属性。
后面的代码实际上被认为是View的一部分,只是将View和ViewModel粘合在一起
进一步阅读
更新2:[其他读者]
答案可以解决问题,但这不是MVVM的真正实现。理想情况下,View与可能包含Model对象的ViewModel绑定。看看Channel9上的视频链接或我的博客文章
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句