我有包含 TextBlock 的 UserControl。 我将此 UserControl 添加到 MainPage 中,然后每 1 秒更新一次 TextBlock。 我调试并看到 TextBlock 值已更改,但显示未显示。 我的代码有什么问题吗?
MyDialog.xaml
<UserControl
...
d:DesignHeight="100"
d:DesignWidth="200">
<Grid>
<TextBlock x:Name="forTestDisplay" FontSize="16" TextWrapping="Wrap"
Text="{Binding ForTest, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
</Grid>
</UserControl>
MyDialog.xaml.cs
namespace Test_UserControl
{
public sealed partial class MyDialog : UserControl
{
public MyDialog()
{
this.InitializeComponent();
}
// Dependency Property for binding
public string ForTest
{
get { return (string)GetValue(ForTestProperty); }
set { SetValue(ForTestProperty, value); }
}
public static readonly DependencyProperty ForTestProperty =
DependencyProperty.Register("ForTest", typeof(string), typeof(MyDialog), new PropertyMetadata(null));
}
}
主页.xaml
<Page
...
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<local:MyDialog x:Name="myDialog" />
</Grid>
</Page>
MainPage.xaml.cs
namespace Test_UserControl
{
public sealed partial class MainPage : Page
{
private DispatcherTimer timer;
public MainPage()
{
this.InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, object e)
{
// Update the data in MyDialog
myDialog.ForTest = DateTime.Now.ToString("HH:mm:ss");
}
}
}
建议在UserControl中使用{x:bind}。
对于x:bind,DataContext是当前页面,它会在当前Code-Bebind类中查找该属性。但对于 Binding,默认情况下假定您绑定到标记页面的 DataContext。
可以参考我的回答这里,调试时有Visual Studio中的XAML Binding Failures Window和APP上的Top Tips。