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
相关产品推荐
相关产品推荐

