如何绑定到整个 UI 元素?

How to bind to an entire UI Element?

我有一个包含 WebView 的自定义控件。我还有一个 ViewModel,它在构造函数中接收 WebView 并对其进行修改。它将 WebView 控制传递给修改它的 VM。

本来想做的:

    public static readonly DependencyProperty AccountProperty =
       DependencyProperty.Register("Account", typeof(Account), typeof(AccountViewControl),
           new PropertyMetadata(null));
    public Account Account {
        get { return (Account)GetValue(AccountProperty); }
        set {
            SetValue(AccountProperty, value);
            SiteViewModel SiteVM = new SiteViewModel(wv: wvAccount);
            SiteVM.CurrentAccount = value;
            SiteVM.LoginToSite();
        }
    }

每个控件都有一个名为 wvAccountWebView,它将被传递到 SiteViewModel 构造函数中。但是,由于在使用 DependencyProperty 时绕过了 setter,我必须使用静态 PropertyChanged 事件来调用 SiteVM.LoginToSite,它无法访问控件的 XAML.

我的第一个想法是将 WebView 属性 添加到 SiteVM 并将 UI 的 WebView 绑定到该元素,但是,我不能似乎找到任何方法绑定到整个 UI 元素。

这是我想要实现的目标:

public static readonly DependencyProperty SiteViewModelProperty =
    DependencyProperty.Register("Account", typeof(SiteViewModel), typeof(AccountViewControl),
        new PropertyMetadata(null, OnSiteViewModelChanged));

private static void OnSiteViewModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    SiteViewModel siteVM = (SiteViewModel)e.NewValue;
    siteVM.LoginToSite();
}

我会像这样绑定它:

<WebView {x:Bind=SiteVM.WebView} Visibility="{Binding ShowEditControl, ElementName=accountControl, Converter={ThemeResource InverseVisConverter}}" x:Name="wvAccount" />

有没有办法(或更好的方法)来实现这个目标?

一般来说,我认为大多数开发人员都会同意这是个坏主意。但这并不意味着你不能这样做。假设您的元素名为 MyElement。这样做:

<Page.DataContext>
    <local:MyViewModel Element="{Binding, ElementName=MyElement}" />
</Page.DataContext>

请记住,您在 ViewModel 中创建的元素 属性 属于 UIElement 类型,或者如果您希望它具有更强类型,则为实际元素类型。

祝你好运!