【发布时间】:2011-06-14 13:55:17
【问题描述】:
我有一个 UserControl,我们称它为“Header”。它有一个名为 ProjectID 的 DependencyProperty,这个控件有一个 View Model,我将它设置为 DataContext:
public BillingInfoHeaderControlVM VM
{
get
{
return (BillingInfoHeaderControlVM)DataContext;
}
set
{
DataContext = value;
}
}
public static readonly DependencyProperty ProjectIDProperty =
DependencyProperty.Register("ProjectID", typeof(int), typeof(BillingInfoHeaderControl), new PropertyMetadata();
public int ProjectID
{
set
{
SetValue(ProjectIDProperty, value);
}
get
{
return (int)GetValue(ProjectIDProperty);
}
}
现在我要做的是将控件的 ProjectID 绑定到该控件的 ProjectID:
<controls:Header Grid.Row ="0" x:Name="Header" ProjectID="{Binding ProjectID, Mode=OneWay}"></controls:Header>
现在,当我运行它时,我在 InitializeControl() 方法中收到一个错误,指出“
找不到属性获取方法。
从我阅读的内容来看,这是因为 Binding ProjectID 与控件的数据上下文相关。当然我可以在绑定中设置 ElementName:
<controls:Header Grid.Row ="0" x:Name="Header" ProjectID="{Binding ProjectID, Mode=OneWay, ElementName=ParentControl}"></controls:Header>
但这很难看,老实说,我们不想在使用此控件时记住为该控件执行此操作。我还有什么其他选择?有没有办法将绑定的源设置为使用父级的 DataContext?
【问题讨论】:
-
ProjectID 不也是 ViewModel 的属性吗?如果没有,为什么不呢,这就是 ViewModel 的作用。
标签: c# silverlight data-binding