ViewModel未显示在{x:Bind}中

时间:2016-05-16 19:36:37

标签: c# xaml binding uwp

我在查看模型中将TextBlock Text绑定到字符串时遇到了一个小问题 我遵循了微软的指南,但我无法理解它。

这是视图模型类:

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:Bind}时vm没有出现。

我认为我错过了一些非常简单的事情,如果你能告诉我的话会很好;)

谢谢,

CRowland

3 个答案:

答案 0 :(得分: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"/>

答案 1 :(得分: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:绑定但很好。

答案 2 :(得分:0)

似乎您没有将x:BindMode=OneWay一起使用。默认情况下,x:Bind的{​​{1}}在值更改时不会更新。 Mode=OneTime起作用的原因是它的默认模式与Binding

不同

如果您首先调用x:Bind,然后在不使用Mode =的情况下设置视图模型,则x:Bind将不会获取更改。

此外,如果您在InitializeComponent();之后设置视图模型(如您所做的那样),则需要确保为viewmodel属性触发了属性更改事件,否则x:Bind仍然看不到它。 / p>