Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何绑定到整个UI元素?_C#_Xaml_Winrt Xaml_Dependency Properties - Fatal编程技术网

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
控件来访问元素。谢谢你的帮助,杰瑞。