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

标签 c# wpf model-view-controller

我正在使用 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/

相关文章:

ios - 如何在问卷中制作嵌套问题?我很困惑

objective-c - Controller 是否应该知道iOS应用程序中的NSManagedObjectContext

c# - DataGridView 中的文本框列

c# - 在后台线程中创建可卡住对象时发生资源泄漏

wpf - WCF 服务在没有管理员权限的情况下无法运行

wpf - INotifyPropertyChanged 接口(interface)如何避免内存泄漏?

javascript - 当用户成功/未成功注册时如何在模式弹出窗口中打开消息

c# - Windows Defender 防火墙阻止了 sendgrid

c# - 级联删除所有虚拟集合

c# - MVVM uwp UserControl 以 VM 作为 DataTemplate