Unable to update UWP UI from code behind using Dispatcher

孤街醉人 提交于 2019-12-11 16:14:30

问题


I have a derived class from MediaTransportControls and trying to disable previous and next track buttons based on some events. I wrote following

public class MyMediaTransportControls : MediaTransportControls
{
    public static readonly DependencyProperty IsPreviousTrackButtonEnabledProperty = DependencyProperty.Register(
        "IsPreviousTrackButtonEnabled", typeof(bool), typeof(MyMediaTransportControls), new PropertyMetadata(false, IsPreviousTrackButtonEnabledChangedCallback));

    private static async void IsPreviousTrackButtonEnabledChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var mediaTransportControls = d as MyMediaTransportControls;

        if(mediaTransportControls?.GetTemplateChild("PreviousTrackButton") is Button previousTrackButton)
        {
            await mediaTransportControls.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                previousTrackButton.IsEnabled = (bool)e.NewValue;
            });
        }
    }

    public bool IsPreviousTrackButtonEnabled
    {
        get { return (bool) GetValue(IsPreviousTrackButtonEnabledProperty); }
        set { SetValue(IsPreviousTrackButtonEnabledProperty, value); }
    }
}

I have used data binding to bind IsPreviousTrackButtonEnabled with the ViewModel logic. However, I find that even when previousTrackButton.IsEnabled is set it has no impact on the UI. Sometime, though, when debuging, I can see the impact on UI.

Update

The MediaTransportControls provide its own ControlTemplate and I wish not to create my own template and do data binding with it.


回答1:


Write Notify Property Changed Event Handler

 INotifyPropertyChanged


来源:https://stackoverflow.com/questions/58282831/unable-to-update-uwp-ui-from-code-behind-using-dispatcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!