我有两页MainPage和PlayPage.Inside MainPage我有一个框架和一个文本块,在框架内我有Playpage。当我从播放页面单击按钮时,我更改了一个变量但文本块没有更新。我怎么做? 这是我的代码:
public class Swag
{
public static int swag = 0;
public void Add(int a)
{
swag += a;
}
public void Reduce(int a)
{
swag -= a;
}
public int Get()
{
return swag;
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
MyFrame.Navigate(typeof(PlayPage));
SwagMeasurer.Text = Convert.ToString(Swag.Get());
}
}
public sealed partial class PlayPage : Page
{
public PlayPage()
{
this.InitializeComponent();
}
private void Clicker_Click(object sender, RoutedEventArgs e)
{
Swag.swag += 1;
}
}
答案 0 :(得分:0)
Handling and Raising Events应该是你的新朋友!
public class Swag
{
private static int _swag;
public static void Add(int a)
{
_swag += a;
OnUpdate?.Invoke(new SwagEventArgs(a));
OnAddition?.Invoke(new SwagEventArgs(a));
}
public static void Reduce(int a)
{
_swag -= a;
OnUpdate?.Invoke(new SwagEventArgs(a));
OnSubtraction?.Invoke(new SwagEventArgs(a));
}
public static int Get()
{
return _swag;
}
public static event AddedValueEventHandler OnAddition;
public static event SubtractedValueEventHandler OnSubtraction;
public static event UpdatedValueEventHandler OnUpdate;
public delegate void AddedValueEventHandler(SwagEventArgs e);
public delegate void SubtractedValueEventHandler(SwagEventArgs e);
public delegate void UpdatedValueEventHandler(SwagEventArgs e);
}
请记住,privacy should be respected!
public partial class PlayPage : Page
{
public PlayPage()
{
InitializeComponent();
}
private void Clicker_Sub_Click(object sender, RoutedEventArgs e)
{
Swag.Reduce(1);
}
private void Clicker_Add_Click(object sender, RoutedEventArgs e)
{
Swag.Add(1);
}
}
请注意,我添加了 减法 Button。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyFrame.Navigate(new PlayPage());
SwagMeasurer.Text = Convert.ToString(Swag.Get());
Swag.OnAddition += Swag_Addition;
Swag.OnSubtraction += Swag_OnSubtraction;
Swag.OnUpdate += Swag_OnUpdate;
}
private void Swag_OnUpdate(SwagEventArgs e)
{
SwagMeasurer.Text = Convert.ToString(Swag.Get());
}
private void Swag_OnSubtraction(SwagEventArgs e)
{
LastMode.Text = "That's a negative";
}
private void Swag_Addition(SwagEventArgs e)
{
LastMode.Text = "That's a positive";
}
}
LastMode
也是TextBlock(如果用户已放弃或提高技能级别,则会重新定位。)
public class SwagEventArgs : EventArgs
{
public SwagEventArgs(int value)
{
Value = value;
}
public readonly int Value;
}
SwagEventArgs
将用于将信息存储为event data。