2011-11-16 76 views
0

我試圖解決的問題是相當簡單的,我使用Microsoft.Phone.Controls,我試圖綁定到的ToggleSwitch兩個屬性在我MainPageViewModel所以我可以捕獲ToggleSwitch的狀態,並將其內容從「開/關」改爲「距離/時間」。結合使用卡利(微)兩個或多個控件屬性

我正在做的事情不起作用,這與我從文檔(RTFM ...)中完全沒有想到的約定有關。這不起作用:

using System; 
using System.Windows.Data; 
using System.Collections.Generic; 
using Caliburn.Micro; 
using Microsoft.Phone.Controls; 

public class AppBootstrapper : PhoneBootstrapper 
{ 
    PhoneContainer container; 

    protected override void Configure() 
    { 
     container = new PhoneContainer(RootFrame); 

     container.RegisterPhoneServices(); 
     container.PerRequest<MainPageViewModel>(); 

     AddCustomConventions(); 
    } 

    private static void AddCustomConventions() 
    { 
     ConventionManager.AddElementConvention<ToggleSwitch>(ToggleSwitch.IsCheckedProperty, "IsChecked", "Click") 
      .ApplyBinding = (viewModelType, path, property, element, convention) => 
      { 
       //Default binding to "IsChecked" property 
       if (!ConventionManager.SetBinding(viewModelType, path + ".IsChecked", property, element, convention)) 
        return false; 

       if (!ConventionManager.HasBinding(element, ToggleSwitch.ContentProperty)) 
       { 
        var binding = new Binding(path + ".Content"); 

        BindingOperations.SetBinding(element, ToggleSwitch.ContentProperty, binding); 
       } 

       return true; 
      }; 
    } 
} 

bool fixedDistance = true; 
    public bool FixedDistance 
    { 
     get 
     { 
      return fixedDistance; 
     } 
     set 
     { 
      fixedDistance = value; 
      NotifyOfPropertyChange(() => FixedDistance); 

      if (fixedDistance) 
      { 
       FixedDistanceContent = "Distance"; 
      } 
      else 
      { 
       FixedDistanceContent = "Time"; 
      } 
     } 
    } 

    string fixedDistanceContent; 

    public string FixedDistanceContent 
    { 
     get 
     { 
      return fixedDistanceContent; 
     } 
     set 
     { 
      fixedDistanceContent = value; 
      NotifyOfPropertyChange(() => FixedDistanceContent); 
     } 
    } 

其中ToggleSwitch有XAML Name=FixedDistance

我天真地(顯然不正確)期待ToggleSwitch.IsChecked被綁定到FixedDistance屬性,而ToggleSwitch.Content綁定到FixedDistanceContent

謝謝!

回答

1

它看起來像這樣:

 ConventionManager.AddElementConvention<ToggleSwitch>(
      ToggleSwitch.IsCheckedProperty, 
      "IsChecked", 
      "Click"); 
      .ApplyBinding = (viewModelType, path, property, element, convention) => 
     { 
      if (!ConventionManager.SetBinding(viewModelType, path, property, element, convention)) 
       return false; 

      if (ConventionManager.HasBinding(element, ToggleSwitch.ContentProperty)) return true; 

      var binding = new Binding(path + "Content") { Mode = BindingMode.TwoWay }; 
      BindingOperations.SetBinding(element, ToggleSwitch.ContentProperty, binding); 

      return true; 
     }; 

的伎倆。