You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP中MediaTransportControls的ControlTemplate无法x:绑定UserControl后台数据

解决方案

1. 修正后台属性的访问权限与通知机制

首先把后台的localTime私有字段改为公开属性,并实现INotifyPropertyChanged接口(确保属性值变化时UI能同步更新):

public sealed partial class MainMedia : UserControl, INotifyPropertyChanged
{
    private string _localTime = "My Local Time";
    public string LocalTime
    {
        get => _localTime;
        set
        {
            _localTime = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LocalTime)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public MainMedia()
    {
        this.InitializeComponent();
    }
}

2. 修改ControlTemplate中的绑定方式

由于x:Bind默认绑定上下文是ControlTemplate的TargetType(即MediaTransportControls),无法直接访问外层UserControl的属性,因此改用Binding并通过RelativeSource指定绑定源为父级的UserControl:

<ControlTemplate TargetType="MediaTransportControls">
    <Grid>
        <!-- 注意替换local为你的UserControl所在的命名空间 -->
        <TextBlock Text="{Binding LocalTime, RelativeSource={RelativeSource AncestorType=local:MainMedia}, Mode=OneWay}"/>
    </Grid>
</ControlTemplate>

关键原因说明

  • x:Bind是编译时绑定,默认会在ControlTemplate的目标类型(MediaTransportControls)中查找属性,所以找不到UserControl里的localTime。
  • Binding支持通过RelativeSource向上遍历视觉树,找到外层的MainMedia实例,从而访问其公开属性LocalTime。
  • 绑定只能访问公开成员,因此必须把原来的私有字段改为公开属性。

内容的提问来源于stack exchange,提问作者ricky rocky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:00:16