我试图解决的问题非常简单,我正在使用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
。
谢谢!
答案 0 :(得分: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;
};
诀窍。