我已创建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
更改,显示也不会受到该更改的影响。
答案 0 :(得分:2)
DependencyObject
- 这是不必要的。INotifyPropertyChanged
允许用户界面在属性值发生变化时收到通知,以便进行更新。答案 1 :(得分:0)
尝试实施INotifyPropertyChanged。 (见INotifyPropertyChanged on MSDN)
您必须“告诉”GUI某些值已被更改,并且必须从绑定值重新读取它。