【发布时间】:2015-11-04 05:18:22
【问题描述】:
您好,所有可能访问此主题的人。我试图了解 XAML 数据绑定的基本原理。如您所见,这是一个简单的通用 Windows 程序。
背景:如果代码放置 (A) ,MainPage.xaml 上的绑定元素不会从 DataContext (ClockDispatcher.cs) 接收数据所需位置在类中执行。
MainPage.xaml 上的绑定元素将在代码放置 (B) 时从 DataContext (ClockDispatcher.cs) 接收数据仅测试常规绑定 在类中执行。
当调试任一代码放置选项时,本地窗口显示公共属性“MyClock.Time”IS 正在设置。但是 MainPage.xaml 上的绑定元素只有在执行 CODE PLACEMENT (B) testing general binding only 时才实现。
问题:我的逻辑中是否存在错误,会阻止设置类属性的能力,并将结果传递给关联的绑定元素?请注意,类属性分配发生在 dispatcherTimer_Tick 方法中。
提前感谢您,您花时间和精力帮助我理解这个问题!
最好的问候, DMMcCollum
MainPage.xaml
<Page
x:Class="TestBinding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestBinding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:TestBinding.Models"
mc:Ignorable="d">
<Page.DataContext>
<data:ClockDispatcher />
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="TimeTextBlock" Text="{Binding MyClock.Time, Mode=OneWay}" />
</StackPanel>
</Grid>
ClockDispatcher.cs
namespace TestBinding.Models
{
public class ClockDispatcher
{
//Bound to "TimeTextBlock" on MainPage.xaml
public Models.Clock MyClock { get; private set; } = new Models.Clock();
public ClockDispatcher()
{
//CODE PLACEMENT (B)
//If executed here - WILL set class public property and WILL BE reflected in UI (but not updated as understood)
//MyClock.Time = string.Format("{0}", DateTime.Now.ToString("t"));
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, object e)
{
//CODE PLACEMENT (A)
//if executed here - WILL set class public property and WILL NOT BE reflected in UI (but updates property on each tick interval as understood)
MyClock.Time = string.Format("{0}", DateTime.Now.ToString("t"));
}
}
}
Clock.cs
namespace TestBinding.Models
{
public class Clock
{
public string Time { get; set; }
}
}
【问题讨论】: