【发布时间】:2022-01-08 18:11:37
【问题描述】:
我对 wpf 相当陌生,并试图编写一个扫雷游戏作为练习。我的问题是我无法获取我的Stackpanel 的数据上下文来查找对象row,除非我将整个窗口的数据上下文设置为RowUpper 类,如下面的代码所示。
尝试将行对象作为RowUpper 类的字段或作为MainWindow 类中的普通对象。我想为文本框ZeitAnzeigeTB 提供timeShown 字段的值,以便能够显示计数器。
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
RowUpper row = new RowUpper();
}
//some more code
}
Mainwindow.xaml:
<Window x:Class="MineSweeper.MainWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:QuizApp"
xmlns:minesweeper="clr-namespace:MineSweeper"
mc:Ignorable="d"
Title="MineSweeper" Height="920" Width="920">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="900"/>
</Grid.RowDefinitions>
<StackPanel x:Name="Stackpanel" Grid.Row="0" DataContext="{Binding row}" VerticalAlignment="Top" Height="80">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
//some more buttons and textboxes
<TextBox x:Name="ZeitAnzeigeTB" TextAlignment="Right" DataContext="{Binding timeshown}" Width="389" Height="40" HorizontalAlignment="Left" FontSize="25" Grid.Row="1" IsReadOnly="True" Margin="70 0 0 0" BorderThickness="0" IsTabStop="True"/>
//even more textboxes and buttons
</Grid>
</StackPanel>
</Grid>
</Window>
RowUpper.cs:
namespace MineSweeper
{
public class RowUpper : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public static RowUpper row = new RowUpper();
private int time = 0;
public string timeshown
{
get
{
return timeshown;
}
set
{
timeshown = value;
PropertyChanged(this, new PropertyChangedEventArgs("timeShown"));
}
}
public static void ResetTimer()
{
using Timer Timer = new(1000);
Timer.Start();
Timer.Elapsed += OnTimedEvent;
}
private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
time++;
timeshown = time.ToString();
}
}
}
【问题讨论】:
-
您只能绑定到当前数据上下文的属性上,
row甚至不是MainWindow的成员,它只存在于构造函数内部,而不是在构造函数之前和之后。你也没有在任何地方设置你的DataContext,如果你想绑定到后面代码的属性,你需要this -
作为
return timeshown;来自timeshown属性的getter 的注释将不起作用。您需要该属性的支持字段。 -
哦,是的,谢谢。由于您的提示,它现在可以工作了。看了一整套关于这个的复数课程,但我还不能真正理解它。
标签: c# wpf data-binding