gpt4 book ai didi

c# - MVC 通过 C#/WPF : how to notify view?

转载 作者:行者123 更新时间:2023-11-30 15:09:35 24 4
gpt4 key购买 nike

我正在使用 WPF 接口(interface)在 C# 中非常简单地实现 MVC 模式。

我有一个保持状态的模型。我希望能够在状态发生任何变化时通知模型的 View ,以便 View 可以相应地更新自身。

在 WPF 中执行此操作的最简单的最佳做法是什么?我知道有 PropertyChanged 事件这样的东西,这是我正在寻找的东西还是对我的情况来说太具体了?

谢谢!

最佳答案

是的。实现接口(interface) INotifyPropertyChanged。

一个例子:

主窗口.xaml

<Window x:Class="INotifyChangedDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Label Content="{Binding HitCount}"></Label>
<Button Grid.Row="1" Click="Button_Click">
Hit
</Button>
</Grid>


主窗口.xaml.cs

namespace INotifyChangedDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private MainViewModel _viewModel = new MainViewModel();

public MainWindow()
{
InitializeComponent();
DataContext = _viewModel;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
_viewModel.HitCount = _viewModel.HitCount + 1;
}
}
}

MainViewModel.cs

namespace INotifyChangedDemo
{
public class MainViewModel : INotifyPropertyChanged
{
private int _hitCount;
public int HitCount
{
get
{
return _hitCount;
}
set
{
if (_hitCount == value)
return;

_hitCount = value;
// Notify the listeners that Time property has been changed
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("HitCount"));
}

}
}

public event PropertyChangedEventHandler PropertyChanged;
}
}

为了更好地实现 INotifyChangedProperty,请引用此线程:Automatically INotifyPropertyChanged .

如果您想了解更多关于 MVVM 模式的信息,请参见此处:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

关于c# - MVC 通过 C#/WPF : how to notify view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4262828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com