我有一个绑定(bind)到依赖属性的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.
    }
}

最佳答案

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

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

关于c# - 如何使用PropertyChangedCallBack,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5498517/

10-16 04:41