2016-05-16 65 views
1

我有一个小问题,在我的视图模型中将TextBlock Text绑定到字符串。
我遵循了微软的指导,但我无法得到它的诀窍。ViewModel没有显示在{x:Bind}

这里是视图模型类:

public class LoginPageViewModel 
{ 
    public LoginPageViewModel() 
    { 
     title = "Space Agency"; 
    } 

    public string title { get; set; } 
} 

背后的代码:

public LoginPage() 
    { 
     this.InitializeComponent(); 

     this.vm = new LoginPageViewModel(); 
    } 

    public LoginPageViewModel vm { get; set; } 

和XAML:

<Page 
x:Class="SpaceAgency.LoginPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:SpaceAgency" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"> 
<Grid x:Name="rootGrid" Background="White"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <TextBlock Text="" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
    <Button Content="Login" FontSize="20" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Top"/> 


</Grid> 

问题是虚拟机确实使用时不显示{x:绑定}。

我觉得I'm失去了一些东西很简单,所以将是很好,如果你能告诉我的方式;)

感谢,

CRowland

回答

0

好找到了解决办法喽。

您必须添加对ViewModels文件夹的引用并在XAML中设置DataContext。

<Page 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:SpaceAgency" 
xmlns:ViewModels="using:SpaceAgency.ViewModels" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

x:Class="SpaceAgency.LoginPage" 
mc:Ignorable="d"> 
<Page.DataContext> 
    <ViewModels:LoginPageViewModel/> 
</Page.DataContext> 

现在我可以设置绑定到标题:

<TextBlock Text="{Binding title}" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center"/> 

这不是X:绑定,但it's罚款。

+1

即使这工作你真的应该考虑使用从@Bart了答案 - X:绑定(编译时间绑定)是新的,在我看来更好的WPF绑定解决方案。如果使用得当,它还可以加快应用程序的性能。 – TryToSolveItSimple

1

您忘记在您的构造函数中设置DataContext属性。做到这一切,一切正常。请注意,如果您希望title属性在运行时进行更新,那么您也必须实施INotifyPropertyChanged,但对于一次性的内容,您的解决方案就没有问题。

public sealed partial class LoginPage : Page 
{ 
    public LoginPage() 
    { 
     InitializeComponent(); 

     Vm = new LoginPageViewModel(); 
     DataContext = Vm; 
    } 

    public LoginPageViewModel Vm { get; set; } 
} 

你的XAML届时将有智能感知为X:绑定

<TextBlock Text="{x:Bind Vm.title}" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center"/>