Search code examples
c#uwpuwp-xaml

UWP Display can not update TextBlock value when changed


I have UserControl that contains a TextBlock. I add this UserControl into MainPage, then update TextBlock every 1 seconds. I debug and see that TextBlock value is changed, but display is undisplayed. Is there anything wrong in my code?

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));

    }
}

MainPage.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");
        }
    }
}

Solution

  • It is recommended to use {x:bind} in UserControl.

    For x:bind, the DataContext is current page, it will find the property in the current Code-Bebind class. But for Binding, assumes, by default, that you're binding to the DataContext of your markup page.

    You can refer to my answer here, and there are XAML Binding Failures Window in Visual Studio and Top tips on APP when debugging.