由于 Windows8 还没有充实的 DatePicker,我决定按照其中的一些示例自己动手做。
它本身工作正常,但现在我有日期,我想用它预填充 DatePicker。
我在下面的 DatePicker.xaml.cs 文件中创建了一个属性:
public DateTime dateVal
{
get
{
return m_dateVal;
}
set
{
m_dateVal = value;
}
}
然后在显示 DatePicker 控件的页面中,我尝试绑定(bind)到该属性:
<dp:DatePicker Foreground="Black" Height="100" Margin="10,25" Grid.Column="1" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="1" dateVal="{Binding repairInfoSingle.repairDate, Mode=TwoWay}"/>
但是,进入 DatePicker.xaml.cs 文件时,dateVal 属性从未填充我传递给它的日期。
然后我在输出窗口中得到一个错误:
WinRT information: Failed to assign to property 'aG.Common.DatePicker.dateVal'. [Line: 125 Position: 170]
我希望传递日期,然后在构造函数中我可以通过解析月、日和年来设置 SelectedIndex
值。
最佳答案
如果您想绑定(bind)到一个属性(例如使用 DateVal={Binding ...}
)- DateVal 不能是常规的 CLR 属性。
您需要将其更改为 DependencyProperty
所以在你的例子中:
public DateTime DateVal
{
get { return (DateTime) GetValue(DateValProperty); }
set { SetValue(DateValProperty, value); }
}
public static readonly DependencyProperty DateValProperty =
DependencyProperty.Register("DateVal", typeof(DateTime), typeof(DatePicker),
new PropertyMetadata(DateTime.MinValue));
现在它应该可以正常工作了:
<dp:DatePicker DateVal="{Binding repairInfoSingle.repairDate, Mode=TwoWay}"/>
关于wpf - 用户控件绑定(bind)将值传递给属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180554/