How to use PropertyChangedCallBack

25,284

The DependencyObject is the object that raised the event. You need to cast obj to the type you need. E.g.

TextBox textbox = (TextBox)obj;
textbox.ScrollToEnd();
Share:
25,284
Eamonn McEvoy
Author by

Eamonn McEvoy

Updated on July 09, 2022

Comments

  • Eamonn McEvoy
    Eamonn McEvoy almost 2 years

    I have a TextBox Binded to a dependancy property, I have implemented a PropertyChangedCallBack function, when the text changes I need to call textbox.ScrollToEnd() but I cant since the PropertChanged function need to be static, is there a way around this?

    static FrameworkPropertyMetadata propertyMetaData = new FrameworkPropertyMetadata
    (
        "MyWindow",
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        new PropertyChangedCallback(TextProperty_PropertyChanged)
    );
    
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register
    (
        "TextProperty", 
        typeof(string), 
        typeof(OutputPanel),
        propertyMetaData
    );
    
    private void TextProperty_PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        textbox.ScrollToEnd(); //An object reference is required for the non-static field.
    }
    
    public string Text
    {
        get 
        { 
            return this.GetValue(TextProperty) as string;
        }
        set 
        { 
            this.SetValue(TextProperty, value);
            //textbox.ScrollToEnd(); // I originally called it here but I think it should be in the property changed function. 
        }
    }