tig*_*tig 3 c# silverlight xaml windows-phone-7 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>
Run Code Online (Sandbox Code Playgroud)
{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>
Run Code Online (Sandbox Code Playgroud)
我在这里找到了这个提示: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>
Run Code Online (Sandbox Code Playgroud)
然后您的绑定更改为:
<TextBlock
Name="textCode"
Text="{Binding Path=Code, ElementName=controlName}" />
Run Code Online (Sandbox Code Playgroud)
要显式设置DataContext,您可以执行以下操作:
<TextBlock
Name="textCode"
DataContext="{Binding ElementName=controlName}"
Text="{Binding Path=Code}" />
Run Code Online (Sandbox Code Playgroud)