WPF DependencyProperty不更新GUI

时间:2015-07-29 08:06:44

标签: c# wpf user-controls dependency-properties

我已创建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更改,显示也不会受到该更改的影响。

2 个答案:

答案 0 :(得分:2)

  1. 在99.9%的情况下,您不需要在viewmodel中使用依赖项属性。在这种情况下也是如此。请改用标准CLR属性。
  2. 不要继承DependencyObject - 这是不必要的。
  3. Implement INotifyPropertyChanged允许用户界面在属性值发生变化时收到通知,以便进行更新。

答案 1 :(得分:0)

尝试实施INotifyPropertyChanged。 (见INotifyPropertyChanged on MSDN

您必须“告诉”GUI某些值已被更改,并且必须从绑定值重新读取它。