【发布时间】:2010-12-17 16:17:51
【问题描述】:
我在使用与列表选择器的两种方式绑定时遇到问题。我可以使用 c# 设置值,但不能在 xaml 中的 SelectedItem=".." 中设置。绑定返回正确的值(并且是列表选择器中的值),因为我通过将文本分配给文本块来发送文本。
当页面加载时,listpicker 上使用的绑定会导致System.ArgumentOutOfRangeException
我用来设置它的代码是:
// Update a setting value. If the setting does not exist, add the setting.
public bool AddOrUpdateValue(string key, Object value)
{
bool valueChanged = false;
try
{
// If new value is different, set the new value
if (settingsStorage[key] != value)
{
settingsStorage[key] = value;
valueChanged = true;
}
}
catch (KeyNotFoundException)
{
settingsStorage.Add(key, value);
valueChanged = true;
}
catch (ArgumentException)
{
settingsStorage.Add(key, value);
valueChanged = true;
}
catch (Exception e)
{
Console.WriteLine("Exception occured whilst using IsolatedStorageSettings: " + e.ToString());
}
return valueChanged;
}
// Get the current value of the setting, if not found, set the setting to default value.
public valueType GetValueOrDefault<valueType>(string key, valueType defaultValue)
{
valueType value;
try
{
value = (valueType)settingsStorage[key];
}
catch (KeyNotFoundException)
{
value = defaultValue;
}
catch (ArgumentException)
{
value = defaultValue;
}
return value;
}
public string WeekBeginsSetting
{
get
{
return GetValueOrDefault<string>(WeekBeginsSettingKeyName, WeekBeginsSettingDefault);
}
set
{
AddOrUpdateValue(WeekBeginsSettingKeyName, value);
Save();
}
}
在 xaml 中:
<toolkit:ListPicker x:Name="WeekStartDay"
Header="Week begins on"
SelectedItem="{Binding Source={StaticResource AppSettings},
Path=WeekBeginsSetting,
Mode=TwoWay}">
<sys:String>monday</sys:String>
<sys:String>sunday</sys:String>
</toolkit:ListPicker>
StaticResource AppSettings 是来自单独 .cs 文件的资源。
<phone:PhoneApplicationPage.Resources>
<local:ApplicationSettings x:Key="AppSettings"></local:ApplicationSettings>
</phone:PhoneApplicationPage.Resources>
提前致谢
【问题讨论】:
-
你写
{StaticResource AppSettings}是什么意思?它是在XAML或static class中定义的resource的名称吗? -
是的对不起我忘了提到 AppSettings 是一个单独的类文件
-
是静态类吗?您是否将
{x:Static AppSettings.WeekBeginsSetting}与您当前的绑定混淆了?因为 Silverlight 不支持{x:Static}。 -
对我来说同样的问题,
SelectedItem和SelectedIndex。特别是 Jame 在下面的评论 我可以让 SelectedIndex 工作,但它只是突出显示该项目并且在列表选择器处于非活动状态时不显示它 - 而是显示列表选择器中的第一个值。看看是否有人知道如何解决这个问题。
标签: c# silverlight xaml windows-phone-7