在DependencyProperty中执行一个函数

时间:2014-01-14 22:45:47

标签: c# wpf inotifypropertychanged

,当我更新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,但是 我在那里得到错误: 非静态字段,方法或属性

需要对象引用

4 个答案:

答案 0 :(得分:1)

您的源对象需要实现INotifyPropertyChanged才能使其工作(具有“MyText”属性的对象)。

MSDN上有一个很好的示例实现。

另外,您的datatemplate可以包含在ListBox中,而不是静态资源(如果这是您想要使用该数据模板的唯一位置,可能会更少混淆):

<ListBox>
   <ListBox.ItemTemplate>
       <DataTemplate>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

答案 1 :(得分:1)

text属性不可访问,因为回调函数是静态的。

您需要将obj参数强制转换为'MyTextBlock',然后通过该指针访问对象的属性。

答案 2 :(得分:0)

您希望在这种情况下使用ObservableCollection.CollectionChanged事件

答案 3 :(得分:0)

要为执行DependencyProperty添加逻辑,您可以为每个DependencyPropertyDescriptor定义DependencyProperty,并在您的AddValueChanged中添加必要的逻辑?.自定义类的构造函数。如果你有一个带有Columns属性的名为DefinableGrid的自定义Grid类,那么结果就是(使用C#6&#39; s空条件运算符 public int Columns { get { return (int) GetValue(ColumnsDependencyProperty); } set { SetValue(ColumnsDependencyProperty, value); } } public static readonly DependencyProperty ColumnsDependencyProperty = DependencyProperty.Register(nameof(Columns), typeof(int), typeof(DefinableGrid), new PropertyMetadata(0)); DependencyPropertyDescriptor ColumnsPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ColumnsDependencyProperty, typeof(DefinableGrid)); public GridEx() { ColumnsPropertyDescriptor?.AddValueChanged(this, delegate { ColumnDefinitions.Clear(); for (int i = 0; i < Columns; i++) ColumnDefinitions.Add(new ColumnDefinition()); }); } ):

$this->_controller->viewVars
相关问题