WPF-绑定到用户控件依赖项属性失败

WPF-绑定到用户控件依赖项属性失败,wpf,dependency-properties,Wpf,Dependency Properties,我有一个绑定到ObservableCollection的控制项组。如果将每个项目的ItemTemplate设置为TextBlock,则其工作方式如下: <DataTemplate x:Key="SampleTemplate"> <TextBlock Text="{Binding FirstName}"/> </DataTemplate> 在主窗口的ItemTemplate中,我将其更改为: <DataTemplate x:Key="SampleTe

我有一个绑定到ObservableCollection的控制项组。如果将每个项目的ItemTemplate设置为TextBlock,则其工作方式如下:

<DataTemplate x:Key="SampleTemplate">
  <TextBlock Text="{Binding FirstName}"/>
</DataTemplate>
在主窗口的ItemTemplate中,我将其更改为:

<DataTemplate x:Key="SampleTemplate">
  <local:SampleControl SomeValue="{Binding FirstName}"/>
</DataTemplate>


但这是行不通的。我不知道为什么当相同的绑定对MainWindow中的TextBlock工作正常时,该绑定会失败。我在这里做错了什么?

我可以看到很多错误,可能是这些东西打破了这一点:

public static DependencyProperty SomeValueProperty = DependencyProperty.Register(
  "SomeValue", typeof(String), typeof(SampleControl), 
  new FrameworkPropertyMetaData(new PropertyChangedCallback(OnSomeValueChanged)));

private static void OnSomeValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  ((d as SampleControl).DataContext as UserControlViewModel).Name = e.NewValue;
}

public string SomeValue
{
  get
  {
    return (string)GetValue(SomeValueProperty);
  }
  set
  {
    SetValue(SomeValueProperty, value);
  } 
}

注意,我使用的是
字符串
,而不是
对象
。并且,在更改
属性changedCallback
中的值方面做额外的工作。而且,我只是在
SomeValue
POCO中做基础工作,因为真正的工作是在
SetValue
中完成的。同样值得注意的是,我没有做任何异常处理,这也可能是您的错误…如果set的
.Name
调用在当前代码中失败,然后,
SetValue
从不点击

这里需要注意的重要一点是,
SomeValue
的setter只是一种方便,可以提供一种简单的方法来设置依赖属性的值(它有其他用途,但在这里不相关)。依赖属性系统仍然可以更改属性的值,而无需通过setter。如果你想对每次更改执行一些操作,请按照Justin的建议注册一个属性更改处理程序。谢谢Justin和Tim。我确实看到了这个错误,并且已经纠正了它,当我将常量值传递为“123”时,它可以正常工作,但它不适用于绑定:我一直收到错误:BindingExpression路径错误:“未在“object”上找到FirstName”属性
public static DependencyProperty SomeValueProperty = DependencyProperty.Register(
  "SomeValue", typeof(String), typeof(SampleControl), 
  new FrameworkPropertyMetaData(new PropertyChangedCallback(OnSomeValueChanged)));

private static void OnSomeValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  ((d as SampleControl).DataContext as UserControlViewModel).Name = e.NewValue;
}

public string SomeValue
{
  get
  {
    return (string)GetValue(SomeValueProperty);
  }
  set
  {
    SetValue(SomeValueProperty, value);
  } 
}