MVVM using WPF and C#
本文关键字:and WPF using MVVM | 更新日期: 2023-09-27 18:09:53
我最近从WinForms转移到WPF,我发现很难区分ViewModel和View。我在ViewModel中设计整个视图。尽管它有效,但我确信它不是正确的方法。
无论如何我可以分开视图和ViewModel不修改太多?我对此做了一些研究,但没有多大帮助。
编辑
XAML
<Window x:Class="PackageDeliveryTool.FolderCheck"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="350" Width="640" ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True" Cursor="Arrow" Closing="Window_Closing">
<!-- From here is the XAML view code which includes button/Grid/StackPanel etc -->
</Window>
我有单独的CS文件模型。它有属性和propertyChanged Events.
这是特定窗口的XAML.Cs文件。有动作和模型对象,
public partial class CopyMessageWindow : Window
{
Model m = new Model("someValue");
public CopyMessageWindow()
{
InitializeComponent();
}
public void StartButton_Click(object sender, RoutedEventArgs e){
//Some code goes here uses Model instance
}
public void OtherLogicMethod(int val){
//Some other logic not related to UI, but to Background program. Also uses Model Instance
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
//When cancel button is clicked, uses Model instance
}
}
EDITx2
我已经写了很多代码。我需要一个更简单的方法来分离视图和ViewModel。
按以下步骤操作:
1。创建您的模型:
public class Model
{
public string Name { get; set; }
}
2。创建你的ViewModel,它将是你的视图DataContext:
public class MainViewModel : BindableBase
{
public MainViewModel()
{
_model = new Model {Name = "Test"};
}
private Model _model;
public Model Model
{
get
{
return _model;
}
set
{
_model = value;
OnPropertyChanged("Model");
}
}
}
3。为了实现完全分离的MVVM模式,让view.cs为空:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
4。创建视图并将DataContext设置为ViewModel:
<Window x:Class="WpfApplication1.MainWindow"
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"
mc:Ignorable="d"
DataContext="{StaticResource MainViewModel}"><Grid><TextBlock Text="{Binding Model.Name, Mode=TwoWay}"/></Grid></Window>
5。实现你的BindableBase:
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}