首先,您必须创建 DataContext 并将其绑定到您的 PhoneApplicationPage。看起来是这样的
DataContext="{Binding Search, Source={StaticResource Locator}}"
这是常用的绑定,有很多很好的教程,这里就不解释了。
然后在 DataContext 中,创建反映单选按钮的属性。
private int _radiusRadio;
public int RadiusRadio
{
get
{
return _radiusRadio;
}
set
{
if (value != -1)
{
if (Set(() => RadiusRadio, ref _radiusRadio, value))
{
IsDirty = true;
}
}
}
}
在 _radiusRadio 中存储选择的值。我正在使用框架MVVM light,我也推荐它,这就是我在那里设置 IsDirty 属性的原因。否则,您应该像往常一样实现“经典”NotifyChanging 和 NotifyChanged 事件。
这里唯一的区别是,如果将值设置为 -1,则什么也不做。这是因为选择单选按钮时 windows-phone 的奇怪行为。当您第一次运行应用程序并使用单选按钮访问页面时,它可以在没有它的情况下工作。但是当您离开该页面并返回时,它会开始发送您不期望的值。
现在我们准备好创建我们的转换器了。转换器也是windos手机中数据绑定的典型东西。
这里是转换器的代码(你可以复制粘贴,任何单选按钮都一样)
public class RadioButtonConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || parameter == null)
{
return false;
}
int index = (int)value;
int parIndex = Int32.Parse((string)parameter);
return index == parIndex;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter == null || (bool)value == false)
{
return -1;
}
return Int32.Parse((string)parameter);
}
}
要添加转换器,你必须添加这个
xmlns:converters="clr-namespace:MyGreatApp.Converters" 到PhoneApplicationPage
然后定义具体的Converter
<phone:PhoneApplicationPage.Resources>
<converters:RadioButtonConverter x:Key="Radius" />
</phone:PhoneApplicationPage.Resources>
现在您可以使用数据绑定了 >
<RadioButton Content="5" GroupName="Radius" IsChecked="{Binding RadiusRadio, Converter={StaticResource Radius}, ConverterParameter=1, Mode=TwoWay}" />
<RadioButton Content="10" GroupName="Radius" IsChecked="{Binding RadiusRadio, Converter={StaticResource Radius}, ConverterParameter=2, Mode=TwoWay}" />
<RadioButton Content="20" GroupName="Radius" IsChecked="{Binding RadiusRadio, Converter={StaticResource Radius}, ConverterParameter=3, Mode=TwoWay}" />
<RadioButton Content="50" GroupName="Radius" IsChecked="{Binding RadiusRadio, Converter={StaticResource Radius}, ConverterParameter=4, Mode=TwoWay}" />
<RadioButton Content="All" GroupName="Radius" IsChecked="{Binding RadiusRadio, Converter={StaticResource Radius}, ConverterParameter=5, Mode=TwoWay}" />
如您所见,convert-parameter 定义了哪个单选按钮是哪个。当您选择一个时,它将存储在您的private int _radiusRadio;
在您的数据上下文中,您可以创建自己的“转换器”,以获取您想要的值,而不是看起来像这样的“1,2,3,4,5”(请注意,这只是可选的“最佳-practice”我正在使用)>
public int Radius
{
get
{
if (_radiusRadio == 1)
{
return 5;
}
if (_radiusRadio == 2)
{
return 10;
}
if (_radiusRadio == 3)
{
return 20;
}
if (_radiusRadio == 4)
{
return 50;
}
if (_radiusRadio == 5)
{
return 0;
}
return 0;
}
}