绑定到WebBrowser的附加属性不起作用

时间:2018-09-03 17:45:54

标签: c# wpf mvvm binding webbrowser-control

我一直在寻找一种从WPF WebBrowser控件中提取HTML的方法。我发现的两个最佳选择是将客户附加属性绑定到应用程序中的属性,或者从WebBrowser控件构建新控件。考虑到我的知识水平和(到目前为止,我确实只需要一次)我选择了第一个。我什至考虑打破MVVM风格并使用后台代码,但我决定不放弃绑定。

我找到了几个有关创建附加属性的示例,最后从这里Here选择了这个示例:

namespace CumminsInvoiceTool.HelperClasses
{
    public static class WebBrowserExtentions
    {
        public static readonly DependencyProperty DocumentProperty =
            DependencyProperty.RegisterAttached("Document", typeof(string), typeof(WebBrowserExtentions), new UIPropertyMetadata(null, DocumentPropertyChanged));

        public static string GetDocument(DependencyObject element)
        {
            return (string)element.GetValue(DocumentProperty);
        }

        public static void SetDocument(DependencyObject element, string value)
        {
            element.SetValue(DocumentProperty, value);
        }

        public static void DocumentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            WebBrowser browser = target as WebBrowser;
            if (browser != null)
            {
                string document = e.NewValue as string;
                browser.NavigateToString(document);
            }
        }
    }
}

我还为WebBrowser控件在xaml中添加了以下内容(我尝试过在xaml中使用“ Path =“和不使用“ Path =”:

<WebBrowser local:WebBrowserExtentions.Document="{Binding Path=PageCode}" Source="https://www.cummins-distributors.com/"/>

“我的视图”具有选项卡控件,一个选项卡具有WebBrowser控件,另一个选项卡具有文本框。当我单击获取代码时,viewModel运行一个函数来将绑定到文本框的属性设置为WebBrowser的附加属性所绑定的字符串。下面是我的ViewModel的代码。

namespace CumminsInvoiceTool.ViewModels
{
    class ShellViewModel : Screen
    {

        private string _browserContent;

        public string BrowserContent
        {
            get { return _browserContent; }
            set {
                _browserContent = value;
                NotifyOfPropertyChange(() => BrowserContent);
            }
        }

        private string _pageCode;

        public string PageCode
        {
            get { return _pageCode; }
            set {
                _pageCode = value;
                NotifyOfPropertyChange(() => PageCode);
            }
        }


        public void StartProgressCommand()
        {

        }

        public void GetContent()
        {
            if (!string.IsNullOrEmpty(PageCode))
            {
                BrowserContent = PageCode;
            }
            else
            {
                MessageBox.Show("There is no cintent to show", "No content Error", MessageBoxButton.OK);

            }
        }

    }
}

该应用程序会编译并运行,但是当我单击“获取代码”时,我收到的“ PageCode”消息框为空。

当我在按钮的功能开头设置断点时,PageCode字符串显示为“ null”。

这是一个问题,因为我正在使用Caliburn.Micro还是缺少其他东西?

-------编辑评论----------

该按钮在上面的“ ShellViewModel”代码中调用GetContent()。我知道该按钮已绑定并且可以正常工作,因为该应用程序显示了我设置的自定义消息框,以便在“ pageCode”为null或为空时告诉我。

文本框如下:

<TextBox x:Name="BrowserContent"/>

0 个答案:

没有答案
相关问题