WPF DependencyProperty not updating GUI

本文关键字:GUI updating not DependencyProperty WPF | 更新日期: 2023-09-27 18:05:29

我创建了一个UserControl,它需要显示时间和日期,并且能够在button click上添加1小时。
XAML:

<UserControl x:Class="Test.UserControls.TestUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:Test.UserControls"
         xmlns:viewModels="clr-namespace:Test.UserControls"
         x:Name="MyTestUserControl">
<UserControl.DataContext>
    <viewModels:TestUserControlViewModel/>
</UserControl.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBox Text="{Binding SelectedDateTime}"/>
    <Popup IsOpen="True">
        <Button Content="Add Hour" Command="{Binding AddHourCommand}"/>
    </Popup>
</Grid>

视图模型:

public class TestUserControlViewModel : DependencyObject
{
    public DateTime SelectedDateTime
    {
        get { return (DateTime)GetValue(SelectedDateTimeProperty); }
        set
        {
            //this gets called
            SetValue(SelectedDateTimeProperty, value);
        }
    }
    public static readonly DependencyProperty SelectedDateTimeProperty =
        DependencyProperty.Register("SelectedDateTime",
            typeof(DateTime),
            typeof(TestUserControl),
            new PropertyMetadata(DateTime.Now));

    #region AddHour Command
    private CommandBase _addHourCommand;
    public CommandBase AddHourCommand
    {
        get { return _addHourCommand ?? (_addHourCommand = new CommandBase(AddHour)); }
    }
    private void AddHour(object obj)
    {
        //this gets called
        SelectedDateTime = SelectedDateTime.AddHours(1);
        //Selected date is changed
    }
    #endregion
}

然而,即使实际的DependencyProperty改变,显示也不受这种变化的影响。

WPF DependencyProperty not updating GUI

  1. 在99.9%的情况下,你不需要在视图模型中使用依赖属性。在这种情况下也是如此。请使用标准的CLR属性。
  2. 不要继承DependencyObject,这是不必要的。
  3. 实现INotifyPropertyChanged,允许UI在属性值改变时获得通知,以便更新。

尝试实现INotifyPropertyChanged。(见MSDN上INotifyPropertyChanged)

你必须"告诉"GUI某个值已经改变了,它必须从绑定值中重新读取它。