標籤:
在WP8.1中,應用程式列按鈕已經可以支援綁定了,而且提供了一種AppBarToggleButton類型,相當於一種開關按鈕,這種按鈕有一個屬性IsChecked,標記是否為選中狀態。
於是想當然的,將IsChecked綁定到某個屬性上,並設定為雙向繫結。結果卻發現,不起作用,該屬性變化時,無法通知AppBarToggleButton的IsChecked屬性變更。
於是寫了一個擴充屬性來實現這個目的,代碼如下:
public class ToggleButtonProperties { public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.RegisterAttached("IsChecked", typeof(bool), typeof(ToggleButtonProperties), new PropertyMetadata(false, OnChanged)); public static bool GetIsChecked(DependencyObject obj) { return (bool)obj.GetValue(IsCheckedProperty); } public static void SetIsChecked(DependencyObject obj, bool value) { obj.SetValue(IsCheckedProperty, value); } private static void OnChanged(DependencyObject o, DependencyPropertyChangedEventArgs args) { ToggleButton tb = o as ToggleButton; if (null != tb) tb.IsChecked = (bool)args.NewValue; } }
使用的時候這樣綁定:
<AppBarToggleButton Icon="Comment" Label="評論" controlHelper:ToggleButtonProperties.IsChecked="{Binding IsShowComments}" Command="{Binding CommandNavToComments}" />
這樣就可以同步屬性的變化了。
Windows Phone 8.1中AppBarToggleButton的綁定問題