我正在尝试使用数据绑定创建WPF应用程序。我已经完成了它显示here但我的标签在更改时没有更新值。我认为原因是, PropertyChanged 等于 null
这是我的XAML:
<Window x:Name="MainWindow1" x:Class="Gui.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:Gui"
mc:Ignorable="d"
Title="MainWindow" Height="315.448" Width="1131.79" ResizeMode="NoResize" Background="#FFFDF9F9">
<Grid Margin="0,0,2,0">
<Label x:Name="stopWatchMethod1" Content="{Binding Path=TimeMethod1, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="343,69,0,0" VerticalAlignment="Top" Height="28" Width="440"/>
</Grid>
</Window>
我的代码背后是这样的:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
private string timeMethod1 = "---";
public string TimeMethod1
{
get { return timeMethod1; }
set
{
timeMethod1 = value;
NotifyPropertyChanged();
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我正在设置值:
ts = stopWatch.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
TimeMethod1 = elapsedTime;
答案 0 :(得分:1)
您没有设置DataContext
。
在构造函数中写:
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
这使您的控件可以监听由MainWindow
(DataContext
)
答案 1 :(得分:0)
您的代码出现了一些错误。我纠正了它。属性名称未定义。请查看以下代码。它应该工作。
public string TimeMethod1
{
get { return timeMethod1; }
set
{
timeMethod1 = value;
NotifyPropertyChanged("TimeMethod1");
}
}