【发布时间】: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();
}
}
每个控件都有一个名为wvAccount 的WebView,它将被传递到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'参数是控件类的实例吗?我在工作,但我回家后会试一试?
-
好吧,我该死的……它成功了!欣赏它,伙计。如果你想创建和回答,我一定会把它标记为答案:)
-
我认为
DependencyObject是Account属性,而不是整个Custom Control
标签: c# xaml winrt-xaml dependency-properties