MVC via C # / WPF: how to notify opinion?

I am making a very simple implementation of the MVC pattern in C # with the WPF interface.

I have a stateful model. I want to be able to notify the model view when something changes state so that the view can update accordingly.

What is the easiest best practice for this in WPF? I know that there is such a thing as a PropertyChanged event, is this what I'm looking for, or is it too specific for my situation?

Thank!

+3
source share
2 answers

Yes. Implement the INotifyPropertyChanged interface.

Example:

MainWindow.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>


MainWindow.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 : INotifyPropertyChanged.

MVVM, . : http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

+3

, PropertyChanged , , . , :

<TextBlock Text="{Binding Name}" />

:

string _name;
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
        RaisePropertyChanged("Name");
    }
}

, /, RaisePropertyChanged. Galavoft MVVM, , MVC.

, .

+2

Source: https://habr.com/ru/post/1776596/


All Articles