Подключи библиотеку MvvmLight
. Почитай про паттерн MVVM
. Не обязательно, чтобы он рассказывался на примере именно UWP
, можно и для WPF
найти, там разницы никакой в самом подходе. Разве что в WPF
будет MainViewModel
не в Code behind
класса MainWindow
, а в каком-нибудь ViewModelLocator
или в XAML
задаваться напрямую в качестве DataContext
.
Пример приложения с использованием паттерна MVVM
.
Ответ на твой вопрос, как сделать, чтобы обновлялось значение другого класса и заодно пример с обновлением UI
ViewModels/MainViewModel.cs
using System;
using GalaSoft.MvvmLight;
namespace UpdateDateTime.ViewModels
{
public class MainViewModel : ViewModelBase
{
private DateTime _date;
public DateTime Date
{
get { return _date; }
set
{
if (Set(ref _date, value))
{
OnDateChanged();
}
}
}
public event EventHandler DateChanged;
public MainViewModel()
{
Date = DateTime.Now;
}
public void IncreaseDate()
{
Date = Date.AddYears(1);
}
protected void OnDateChanged()
{
DateChanged?.Invoke(this, EventArgs.Empty);
}
}
}
Views/MainPage.xaml
<Page
x:Class="UpdateDateTime.MainPage"
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:local="using:UpdateDateTime"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Top" />
</Style>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Top" />
</Style>
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<TextBlock
Style="{StaticResource TextBlockStyle}"
Grid.Row="0"
Margin="0,45,0,0"
Text="{x:Bind ViewModel.Date, Mode=OneWay, FallbackValue='0000'}" />
<TextBlock
Style="{StaticResource TextBlockStyle}"
Grid.Row="1"
Text="{x:Bind ViewModel.Date, Mode=OneWay, FallbackValue='0000'}" />
<Button
Style="{StaticResource ButtonStyle}"
Grid.Row="2"
Click="{x:Bind ViewModel.IncreaseDate}"
Content="Увеличить" />
</Grid>
</Page>
Views/MainPage.xaml.cs
using System;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using UpdateDateTime.ViewModels;
namespace UpdateDateTime
{
public sealed partial class MainPage : Page
{
private SomeClass _someClass;
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
nameof(ViewModel), typeof(MainViewModel), typeof(MainPage), new PropertyMetadata(default(MainViewModel)));
public MainViewModel ViewModel
{
get { return (MainViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public MainPage()
{
InitializeComponent();
// Отписываться не обязательно, так как у COM объектов слабые ссылки (все события UWP классов)
Unloaded += OnUnloaded;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
ViewModel.DateChanged -= OnDateChanged;
ViewModel = null;
// Если в UI есть x:Bind, то нужно вызывать
Bindings.StopTracking();
}
private void OnDateChanged(object sender, EventArgs e)
{
_someClass.UpdateDays(((MainViewModel)sender).Date.Year, 2);
Debug.WriteLine($"Days: {_someClass.Days.ToString()}");
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
_someClass = new SomeClass();
ViewModel = new MainViewModel();
ViewModel.DateChanged += OnDateChanged;
base.OnNavigatedTo(e);
}
}
}
class
событие типаEventHandler<int>
, а вclass2
подпишитесь на него. После строкиTextBlock1.Text = i.ToString();
вызывайте это событие и передавайте через его второй аргумент значениеi
.