0

我已经能够轻松地在页面之间传输对象,但现在我无法在 xaml 标记中显示数据。

这是存储在应用程序的 sdf 文件中的 Quote 实体:

[Table]
    public class Quote
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
        public int Id { get; set; }


        [Column(CanBeNull = false)]
        public string QuoteOfTheDay { get; set; }


        [Column(CanBeNull = false)]
        public string SaidBy { get; set; }


        [Column(CanBeNull = true)]
        public string Context { get; set; }


        [Column(CanBeNull = true)]
        public string Episode { get; set; }


        [Column(CanBeNull = true)]
        public string Season { get; set; }
    }

这是后面的代码:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    DataContext = this;

    var quote = PhoneApplicationService.Current.State["q"];             

    Quote quoteToDisplay = (Quote)quote;       
}

public static readonly DependencyProperty QuoteToDisplayProperty = DependencyProperty.Register(
    "QuoteToDisplay", typeof(Quote), typeof(PhoneApplicationPage), new PropertyMetadata(default(Quote)));

public Quote QuouteToDisplay
{
    get { return (Quote)GetValue(QuoteToDisplayProperty); }
    set { SetValue(QuoteToDisplayProperty, value); }
}

xml:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <TextBlock FontSize="36" FontFamily="Verdana" FontWeight="ExtraBlack" Text="{Binding QuoteToDisplay.QuoteOfTheDay}" />
    </Grid>

我得到了要在 xaml 中显示的确切数据。我想在 TextBlock 中显示 QuoteOfTheDay 属性。但是每次我尝试使用 {Binding} 时,TextBlock 总是为空的。当我也尝试使用绑定时,智能感知不建议“QuoteOfTheDay”。

我显然错过了一些重要的事情,但我真的看不出它是什么。

4

2 回答 2

2

快速查看您的代码会发现几个问题:

  1. 您正在 C# 代码中初始化一个 TextBlock,并为其指定与您在 XAML 中定义的 TextBlock 相同的名称。这意味着您不会更改实际显示的 XAML TextBlock 的任何属性。
  2. 您正在为您的 TextBlock 指定一个 DataContext quoteToDisplay.QuoteOfTheDay,但是您在 XAML 中的绑定语句是{Binding quoteToDisplay.QuoteOfTheDay},这意味着您正在尝试绑定到一个不存在的层次结构quoteToDisplay.QuoteOfTheDay.quoteToDisplay.QuoteOfTheDay中。由于此错误,您可能会在输出窗口中收到 BindingExpression 错误。

我要做的是:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    DataContext = this;

    var quote = PhoneApplicationService.Current.State["q"];

    QuoteToDisplay = (Quote)quote;
}

public static readonly DependencyProperty QuoteToDisplayProperty = DependencyProperty.Register(
    "QuoteToDisplay", typeof (Quote), typeof (MainPage), new PropertyMetadata(default(Quote)));

public Quote QuoteToDisplay
{
    get { return (Quote) GetValue(QuoteToDisplayProperty); }
    set { SetValue(QuoteToDisplayProperty, value); }
}

在 XAML 中:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <TextBlock FontSize="36" FontFamily="Verdana" FontWeight="ExtraBlack" Text="{Binding QuoteToDisplay.QuoteOfTheDay}" />
</Grid>
于 2014-06-10T14:41:53.157 回答
0

如果在代码隐藏中分配 .Text 属性,为什么要使用 {Binding} ?我认为您必须从 xaml 中删除绑定,或者(这是更好的方法)使用 MVVM。

于 2014-06-10T14:40:49.743 回答