C# 如何绑定到整个UI元素?
我有一个自定义控件,其中包含C# 如何绑定到整个UI元素?,c#,xaml,winrt-xaml,dependency-properties,C#,Xaml,Winrt Xaml,Dependency Properties,我有一个自定义控件,其中包含WebView。我还有一个ViewModel,它在构造函数中接受WebView并对其进行修改。它将WebView控件传递给修改它的VM 最初,我想这样做: public static readonly DependencyProperty AccountProperty = DependencyProperty.Register("Account", typeof(Account), typeof(AccountViewControl),
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" />
是否有一种方法(或更好的方法)来实现这一点?一般来说,我认为大多数开发人员都会同意这是一个坏主意。但这并不意味着你做不到。让我们假设您的元素名为MyElement。这样做:
<Page.DataContext>
<local:MyViewModel Element="{Binding, ElementName=MyElement}" />
</Page.DataContext>
请记住,您在ViewModel中创建的元素属性的类型为UIElement,如果您希望它的类型更强,则为实际的元素类型
祝你好运 在您的OnSiteViewModelChanged中,d参数将是您的WebView。您是否尝试强制转换并使用它?您的意思是“d”参数是控件类的实例?我在工作,但我回家后会试试吗?我会被诅咒的。。。成功了!谢谢你,伙计。如果要创建并回答,我一定会将其标记为答案:)我假设
DependencyObject
将是帐户
属性,而不是整个自定义控件
,我试图使问题变得更加复杂,我可以通过将DependencyObject
转换为MyElement
控件来访问元素。谢谢你的帮助,杰瑞。