,当我更新observableCollection“ MyCollection”中的项目时,我希望我的自定义TextBlock(执行函数并修改其文本。我认为我应该调用函数OnMYDataChanged:
<ListBox ItemsSource="{Binding MyCollection}" ItemTemplate="{StaticResource MyTemplate}" >
<DataTemplate x:Key="MyTemplate" >
<Grid >...
<local:MyTextBlock Path="{Binding MyText}" />
哪里
public class MyTextBlock : TextBlock
{
public string Path
{ get {return (string)GetValue(PathProperty);}
set { SetValue(PathProperty, value); }
}
public static readonly DependencyProperty PathProperty =
DependencyProperty.Register("Path", typeof(string), typeof(MyTextBlock), new PropertyMetadata(OnMyDataChanged));
static void OnMyDataChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
Text = DoSomethingWithText(); //Does not work
}
当我更改一项时,OnMyDataChanged被调用,但是
我在那里出错:
非静态字段,方法或属性需要对象引用
最佳答案
由于回调函数是静态的,因此无法访问text属性。
您需要将obj参数强制转换为“ A TextBlock”,并通过该指针可以访问对象的属性。