【问题标题】:How to bind to an entire UI Element?如何绑定到整个 UI 元素?
【发布时间】:2015-07-21 03:22:52
【问题描述】:

我有一个包含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 添加一个 WebView 属性并将 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" />

是否有办法(或更好的方法)来实现这一点?

【问题讨论】:

  • 在您的 OnSiteViewModelChanged 中,d 参数将是您的 WebView。您是否尝试过投射并使用它?
  • 你的意思是'd'参数是控件类的实例吗?我在工作,但我回家后会试一试?
  • 好吧,我该死的……它成功了!欣赏它,伙计。如果你想创建和回答,我一定会把它标记为答案:)
  • 我认为DependencyObjectAccount 属性,而不是整个Custom Control

标签: c# xaml winrt-xaml dependency-properties


【解决方案1】:

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

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

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

祝你好运!

【讨论】:

  • 幸运的是,我试图让问题变得更复杂,我可以通过将DependencyObject 转换为MyElement 控件来访问该元素。感谢您的帮助,杰瑞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2013-05-04
相关资源
最近更新 更多