我正嘗試使用數據綁定來創建WPF應用程序。我已經完成了它的顯示here,但是我的標籤在更改時沒有更新該值。我認爲其中的原因是,的PropertyChanged等於空c#爲什麼我的Databinding沒有更新PropertyChanged事件?
這是我的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;
你設置的DataContext? –
你是否在代碼中設置了datacontext? datacontext的類是否實現INotifyPropertyChanged? 'ViewModel:INotifyPropertyChanged' –
避免數據綁定到Label.Content屬性https://msdn.microsoft.com/en-us/library/bb613560%28v=vs.100%29.aspx – adminSoftDK