簡體   English   中英

如何覆蓋ViewModel DataContext,以便綁定到View中的對象(Mvvm-Light)?

[英]How do I override the ViewModel DataContext so I can bind to objects in the View (Mvvm-Light)?

我正在使用Mvvm-Light並且一直忽略了XAML中的綁定到目前為止是如何工作的。

這是我的XAML

<phone:PhoneApplicationPage.Resources>
</phone:PhoneApplicationPage.Resources>

<Grid x:Name="LayoutRoot" Background="Transparent">

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,14">
        <TextBlock x:Name="ApplicationTitle" Text="{Binding SecuritySystemName}" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="{Binding PageName}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <TextBlock Name="textCode" 
        DataContext="{WHAT GOES HERE to bind to properties on my View (SecurityPanelPage class)}"    
        Text="{Binding Path=Code}" />

</Grid>

{Binding SecuritySystemName}和{Binding PageName}正確綁定到我的ViewModel(SecuirtyPanelViewModel)。 但我希望TextBlock元素中的{Binding Code}綁定到我的VIEW(而不是ViewModel)。

我搜索並搜索了解釋DataContext和Binding支持的語法和值的文檔和示例。 沒有任何幫助。

我想知道的是我如何設置一個DataContext(或指定一個指向我的View對象的{Binding ...}中的東西。我嘗試過“Self”和各種“RelativeSource”的東西,但沒有猜測是沒有效率的,因為在解析XAML之前往返調試器的過程太長了。

謝謝。

更新 - 我找到了一個讓我感動的答案,但我仍然沒有理解,所以我對下面的精美海報提出了跟進問題。

這是有效的:

<phone:PhoneApplicationPage x:Name="ThisPage">
   <TextBlock Name="textCode" Text="{Binding Code, ElementName=ThisPage"/>
</phone:PhoneApplicationPage>

我在這里找到了這個提示: http//bursjootech.blogspot.com/2007/12/bind-from-xaml-to-local-property-in.html

他以不同的方式提出這個問題:如何“在XAML中綁定到代碼隱藏的本地財產”。

我仍然不明白下面提供的兩個解決方案。 以下更多問題......

通常,當您使用MVVM時,幾乎所有可綁定屬性都在ViewModel上,而不在View上。 但是,顯然有時您需要創建具有屬性的組件控件。 你能解釋一下這個屬性是什么以及為什么它只需要成為視圖中的一個屬性?

那就是說......我猜你的SecurityPanelPage是顯示XAML的視圖?

您可以為控件指定名稱,然后使用ElementName綁定。 這樣您就不需要設置DataContext。

<phone:PhoneApplicationPage
  x:Name="controlName"
  x:Class="SomeNamespace.SecurityPanelPage">
</phone:PhoneApplicationPage>

然后您的綁定更改為:

<TextBlock
  Name="textCode" 
  Text="{Binding Path=Code, ElementName=controlName}" />

要顯式設置DataContext,您可以執行以下操作:

<TextBlock
  Name="textCode" 
  DataContext="{Binding ElementName=controlName}"
  Text="{Binding Path=Code}" />

如果我沒錯,您可以將app.xaml中的資源添加到您想要的視圖中。

AE:

xmlns:crap="clr-namespace:Application.Views"
<Application.Resources>
    <ResourceDictionary>
        <crap:MyViewPage x:Key="MyViewPage" />
    </ResourceDictionary>  
</Application.Resources>

然后使用它像"{Binding MyProperty, source={StaticResource MyViewPage}".

希望這有效/有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM