C# 使用DateTime DependencyProperty在WPF中实现双向绑定
我构建了一个WPF用户控件,其中包括一个日期选择器。我的应用程序是用MVVM设计模式编写的。我希望能够将用户控件插入视图,并将用户控件的DatePicker的SelectedDate属性绑定到视图的ViewModel上的DateTime属性。我希望默认值显示为存储在视图的viewmodel上的值,并且我希望通过与DatePicker交互来更改日期,以更新视图的viewmodel DateTime属性C# 使用DateTime DependencyProperty在WPF中实现双向绑定,c#,wpf,datepicker,dependency-properties,C#,Wpf,Datepicker,Dependency Properties,我构建了一个WPF用户控件,其中包括一个日期选择器。我的应用程序是用MVVM设计模式编写的。我希望能够将用户控件插入视图,并将用户控件的DatePicker的SelectedDate属性绑定到视图的ViewModel上的DateTime属性。我希望默认值显示为存储在视图的viewmodel上的值,并且我希望通过与DatePicker交互来更改日期,以更新视图的viewmodel DateTime属性 ... private DateTime birthdate; public DateTime
...
private DateTime birthdate;
public DateTime Birthdate
{
get { return birthdate; }
set
{
if(birthdate != value)
{
birthdate = value;
NotifyPropertyChanged(() => Birthdate);
}
}
}
...
我成功地看到DatePicker控件中显示了正确的绑定值,但是当我更改日期时,视图的viewmodel的DateTime属性设置器没有启动
这是我对我的用户控件的代码隐藏的内容:
public partial class AgeDiscountUserControl : UserControl
{
public AgeDiscountUserControl()
{
InitializeComponent();
}
public DateTime DateTime
{
get { return (DateTime)GetValue(DateTimeProperty); }
set { SetValue(DateTimeProperty, value); }
}
public static readonly DependencyProperty DateTimeProperty =
DependencyProperty.Register("DateTime", typeof(DateTime), typeof(AgeDiscountUserControl));
}
在我的用户控件的XAML中,我有:
...
xmlns:my="clr-namespace:jkshay.UserControls"
...
<DatePicker Grid.Row="0" SelectedDate="{Binding DateTime, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType=my:AgeDiscountUserControl}}" DockPanel.Dock="Right"/>
...
最后,在我的视图的XAML中,我的AgeDiscountUserControl的绑定是:
...
<uc:AgeDiscountUserControl DateTime="{Binding Birthdate}"/>
...
。。。
...
如前所述,正确的值最初显示在用户控件的DatePicker中,但DatePicker所做的更改不会影响绑定属性
...
private DateTime birthdate;
public DateTime Birthdate
{
get { return birthdate; }
set
{
if(birthdate != value)
{
birthdate = value;
NotifyPropertyChanged(() => Birthdate);
}
}
}
...
我是在这里遗漏了什么,还是我只是对从属财产有一个完全的误解
我应该提到,如果我在视图中插入日期选择器并将其绑定到viewmodel的Birthdate属性,它将按预期工作。根据Sinatr的建议,我在视图的XAML中添加了Mode=TwoWay设置,现在一切都按预期工作 更新的相关XAML是:
<uc:AgeDiscountUserControl DateTime="{Binding Birthdate, Mode=TwoWay}"/>
我现在看到我的生日设定器在与用户控件交互时启动。感谢您的建议,Sinatr。正如您已经了解的那样,
绑定必须是双向的,以确保在目标控件的值更改时更新源。但是您不需要显式地这样做:您可能希望将双向绑定设置为DateTime
属性的默认值。您可以通过在注册依赖项属性时指定标志来完成此操作:
public static readonly DependencyProperty DateTimeProperty =
DependencyProperty.Register(
"DateTime",
typeof(DateTime),
typeof(AgeDiscountUserControl),
new FrameworkPropertyMetadata(
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault // <--
)
);
public静态只读DependencyProperty DateTimeProperty=
从属属性。寄存器(
“日期时间”,
类型(日期时间),
类型(AgeDiscountUserControl),
新框架属性元数据(
FrameworkPropertyMetadataOptions.bindstwoway默认//您是否尝试过Mode=TwoWay
?我原以为默认值是双向的,但我会试一试。就是这样,Sinatr!谢谢!马上回复帖子。只需删除问题。它对其他人来说不会很有用。关于默认双向,它必须在Depende中定义ncyProperty.Register()
,请参阅。@Sinatr它对我很有用,即使在4年之后!