案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
优先级绑定,会依次去读取绑定的值。
知识点:
1、PriorityBinding: 描述附加到单个绑定目标属性的 System.Windows.Data.Binding 对象的集合,该属性从成功生成值的集合中的第一个绑定接收其值。
2、Binding.IsAsync: 获取或设置一个值,该值表示 System.Windows.Data.Binding 是否应异步获取和设置值。
异步时:IsAsync = true,演示效果:在设置第一个绑定值后展示,再设置第二个绑定值,能看到绑定值自动切换。
同步时:IsAsync = false, 演示效果:在设置完第一个绑定值不回到界面继续设置第二个绑定值,最后不能看到绑定值切换的效果,只能看到最后一个绑定值。
三、分析代码
1、数据源,为了展示依次变换值,所以在读取值时线程睡眠3秒,同时绑定需要设为异步。
public class AsyncDataSource
{
private string _slowerDp;
private string _slowestDp;
public string FastDp { get; set; }
public string SlowerDp
{
get
{
// This simulates a lengthy time before the
// data being bound to is actualy available.
Thread.Sleep(3000);
return _slowerDp;
}
set { _slowerDp = value; }
}
public string SlowestDp
{
get
{
// This simulates a lengthy time before the
// data being bound to is actualy available.
Thread.Sleep(5000);
return _slowestDp;
}
set { _slowestDp = value; }
}
}
2、设置优先级绑定,绑定设置为异步
如果不设置为异步,在同步的情况下,需要设置完所有绑定值后再展示,效果就是只能看到最后一个绑定值。不能看到绑定值切换的过程。
<TextBlock Background="Honeydew" Width="100" HorizontalAlignment="Center">
<TextBlock.Text>
<PriorityBinding FallbackValue="defaultvalue">
<Binding Path="SlowestDp" IsAsync="True"/>
<Binding Path="SlowerDp" IsAsync="True"/>
<Binding Path="FastDp" />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>