在MvvmLight下使用{x:Bind}

来源:转载

One of the XAML-related announcements at Build this year was the availability of compiled bindings. These new bindings can be used instead of the “classic” {Binding} syntax in XAML. Note that this syntax is only available in Windows 10 universal applications, not in WPF yet.


The advantage of compiled bindings over normal bindings is that (wait for it) they are compiled. So there is syntax check by the compiler when you build your project. Also, the bindings will be resolved much faster because they do not rely on reflection during runtime.


For example, if you have the following property in a Windows 10 Universal application page:

public string TimeWhenLoadingPage
{
get
{
return DateTime.Now.ToString("HH:mm:ss");
}
}

Then you can consume this property in the XAML with:

 VerticalAlignment="Center"
FontSize="18"
Text="{x:Bind TimeWhenLoadingPage}" />

Using x:Bind with MVVM


Of course these bindings will react to the PropertyChanged event, just like normal bindings too. So you can use these in an MVVM app without issues. There are also the usual parameters you can use, such as Converter, ConverterParameter, Mode, etc.


The only parameter missing, however, is the Source one. ElementName is also missing from there, but for an MVVM app, Source is more annoying. So how can you do, for instance in an MVVM Light application?


In fact it’s not that hard: Since you can bind to a property of the Page, and since the x:Bind syntax supports access to nested properties, you just have to expose the ViewModel as a property of the Page. In general, we set the ViewModel as the DataContext of the Page, for example with:


 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding Main, Source={StaticResource Locator}}">



Then we can expose the DataContext in the Page with:

public sealed partial class MainPage : Page
{
public MainViewModel Vm
{
get
{
return (MainViewModel)DataContext;
}
}
public MainPage()
{
InitializeComponent();
}
}

(by the way, if you install the MVVM Light Visual Studio extension (VSIX) available on Codeplex, you get code snippets in Visual Studio. One of these has the shortcut mvvmvm and create the code show above, which is a convenient shortcut).


Once this property is exposed, we can use the properties within the ViewModel, for example with:

 VerticalAlignment="Center"
FontSize="18"
Text="{x:Bind Vm.Hello}" />

Hopefully this will help MVVM Light users to take advantage of these new bindings!


转自:这里

分享给朋友:
您可能感兴趣的文章:
随机阅读: