回拨第二次无法正常工作

时间:2016-04-30 15:32:17

标签: c# wpf mvvm

我在下面的代码中遇到了一个问题,即只有在第一次设置DocText时才会调用回调。随后设置DocText不会调用我的回调。我试图通过将相同的字符串设置为DocText属性来重置浏览器的html。

WebBrowser类

 public static readonly DependencyProperty DocumentTextProperty =
 DependencyProperty.Register("DocumentText", typeof(string),
 typeof(WebBrowser), new
 FrameworkPropertyMetadata(string.Empty,TextChangedCallback));

 private static void TextChangedCallback(DependencyObject
 dependencyObject, DependencyPropertyChangedEventArgs
 dependencyPropertyChangedEventArgs)
 { 
    var control = (WebBrowser)dependencyObject;
    control._browser.DocumentText = dependencyPropertyChangedEventArgs.NewValue.ToString();
 }

 public string DocumentText 
 {
     get { return (string)GetValue(DocumentTextProperty); }
     set { SetValue(DocumentTextProperty, value); }
 }

创建Web浏览器实例的工厂类使用浏览器集绑定将依赖项属性绑定到“Doc​​Text”

 if (!String.IsNullOrEmpty(documentTextProperty))
 {
     browser.SetBinding(WebBrowser.DocumentTextProperty,     documentTextProperty);
 }

documentTextProperyt正是从ViewModel类

中设置的
 DocText = "some html string";

 public string DocText
 {
     get
     {
         _docText = if(html != null? html: string.empty);
         return _docText;
     }
     set
     {
         docText = value;
         OnPropertyChanged(() = DocText);
     }
 }

1 个答案:

答案 0 :(得分:0)

看起来Notification不会回归控制(WebBrowser)。请检查INotifyPropertyChanged是否已正确实施。我检查了我的系统中的等效代码,它正常工作。

    public class MaskedTextBox : TextBox
{
    public static readonly DependencyProperty DocumentTextProperty =
         DependencyProperty.Register("DocumentText", typeof(string),
         typeof(MaskedTextBox), new PropertyMetadata(default(string), TextChangedCallback));

    private static void TextChangedCallback(DependencyObject
    dependencyObject, DependencyPropertyChangedEventArgs
    dependencyPropertyChangedEventArgs)
    {
        var control = (MaskedTextBox)dependencyObject;
        control.Text= dependencyPropertyChangedEventArgs.NewValue.ToString();
    }

    public string DocumentText
    {
        get { return (string)GetValue(DocumentTextProperty); }
        set { SetValue(DocumentTextProperty, value); }
    }
}

<StackPanel Margin="50,5,5,50">
        <local:MaskedTextBox x:Name="text1" DocumentText="{Binding ElementName=text2, Path=Text, Mode=OneWay}"/>
        <TextBox x:Name="text2"/>
    </StackPanel>

如果你编辑第二个文本框,它会通过正确调用回调方法来更新第一个文本框!