如何:實作 PriorityBinding
PriorityBinding 在 Windows Presentation Foundation 中,可以藉由指定系結清單來運作。 系結清單會從最高優先順序排序為最低優先順序。 如果最高優先順序系結在處理時成功傳回值,則永遠不需要處理清單中的其他系結。 在較高優先順序的系結成功傳回值之前,最高優先順序系結可能需要很長的時間才能進行評估,否則會使用傳回值的下一個最高優先順序。
範例
為了示範運作方式 PriorityBinding , AsyncDataSource
物件已使用下列三個屬性建立: FastDP
、 SlowerDP
和 SlowestDP
。
的 FastDP
get 存取子會傳回資料成員的值 _fastDP
。
的 get 存取子 SlowerDP
會等候 3 秒,再傳回資料成員的值 _slowerDP
。
的 get 存取子 SlowestDP
會等候 5 秒,再傳回資料成員的值 _slowestDP
。
注意
此範例僅供示範之用。 .NET 指導方針建議用來定義比欄位集慢的量級順序的屬性。 如需詳細資訊,請參閱 在屬性和方法 之間選擇。
public class AsyncDataSource
{
private string _fastDP;
private string _slowerDP;
private string _slowestDP;
public AsyncDataSource()
{
}
public string FastDP
{
get { return _fastDP; }
set { _fastDP = value; }
}
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; }
}
}
Public Class AsyncDataSource
' Properties
Public Property FastDP As String
Get
Return Me._fastDP
End Get
Set(ByVal value As String)
Me._fastDP = value
End Set
End Property
Public Property SlowerDP As String
Get
Thread.Sleep(3000)
Return Me._slowerDP
End Get
Set(ByVal value As String)
Me._slowerDP = value
End Set
End Property
Public Property SlowestDP As String
Get
Thread.Sleep(5000)
Return Me._slowestDP
End Get
Set(ByVal value As String)
Me._slowestDP = value
End Set
End Property
' Fields
Private _fastDP As String
Private _slowerDP As String
Private _slowestDP As String
End Class
屬性 Text 會使用 PriorityBinding 系結至上述 AsyncDS
:
<Window.Resources>
<c:AsyncDataSource SlowestDP="Slowest Value" SlowerDP="Slower Value"
FastDP="Fast Value" x:Key="AsyncDS" />
</Window.Resources>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"
DataContext="{Binding Source={StaticResource AsyncDS}}">
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
HorizontalAlignment="Center">Priority Binding</TextBlock>
<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>
</StackPanel>
當系結引擎處理 Binding 物件時,它會以第一個 Binding 系結至 屬性的 SlowestDP
開頭。 處理這個 Binding 時,它不會成功傳回值,因為它正在睡眠 5 秒,因此會處理下一個 Binding 元素。 下一個 Binding 不會成功傳回值,因為它正在睡眠 3 秒。 接著,系結引擎會移至下一個 Binding 系結至 屬性的專案 FastDP
。 這會 Binding 傳回 「Fast Value」 值。 現在 TextBlock 會顯示 「快速值」值。
經過 3 秒之後, SlowerDP
屬性會傳回 「Slower Value」 值。 接著 TextBlock 會顯示值「慢速值」。
經過 5 秒之後,屬性會 SlowestDP
傳回 「Slowest Value」 值。 該系結具有最高的優先順序,因為它會先列出。 現在 TextBlock 會顯示值「最慢值」。
如需系結成功傳回值的相關資訊,請參閱 PriorityBinding 。