如何使用PropertyChangedCallBack

22

我有一个绑定到依赖属性的TextBox,我已经实现了一个PropertyChangedCallBack函数,当文本改变时,我需要调用textbox.ScrollToEnd(),但我不能这样做,因为PropertChanged函数需要是静态的,有没有解决这个问题的方法?

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. 
    }
}
1个回答

27

DependencyObject是引发事件的对象。您需要将obj强制转换为所需的类型。例如:

TextBox textbox = (TextBox)obj;
textbox.ScrollToEnd();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接