【问题标题】:c# Why is my Databinding not updating an PropertyChanged Event?c# 为什么我的数据绑定没有更新 PropertyChanged 事件?
【发布时间】:2016-05-03 07:52:42
【问题描述】:

我正在尝试使用数据绑定创建 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;

【问题讨论】:

标签: c# wpf data-binding


【解决方案1】:

你没有设置DataContext

在你的构造函数中写:

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
}

这使您的控件能够侦听由您的MainWindowDataContext)触发的属性更改事件

【讨论】:

  • 谢谢,它现在可以工作了。只有我的秒表在运行时没有更新,但我认为这是另一个问题
  • 是的,我同意。我建议您针对该问题打开另一个问题
【解决方案2】:

您的代码有一些错误。我已经纠正了。未定义属性名称。请检查以下代码。它应该可以工作。

public string TimeMethod1
{
        get { return timeMethod1; }
        set
        {
            timeMethod1 = value;

            NotifyPropertyChanged("TimeMethod1");
        }
}

【讨论】:

  • 还是不行。在方法 NotifyPropertyChanged var handler is null ==> 它什么也没做
  • 那么您可能没有正确设置数据上下文。在您的视图的构造函数中,将数据上下文设置为您的视图模型类实例。
  • 好吧,我的构造函数在上面的代码中。我的代码中的所有其他构造函数都没有对我的 UI 做任何事情
  • this.DataContext = this;在您的构造函数中执行此操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2010-09-21
  • 2020-04-21
  • 1970-01-01
相关资源
最近更新 更多