c# - 双向绑定(bind)设置问题

标签 c# silverlight xaml windows-phone-7

我在使用列表选择器进行双向绑定(bind)时遇到问题。我可以使用 c# 设置值,但不能在 xaml 中的 SelectedItem=".." 中设置值。绑定(bind)正在返回正确的值(并且是列表选择器中的一个值),因为我通过将文本分配给文本 block 来向它发送短信。

当页面加载时,列表选择器上使用的绑定(bind)导致 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>

提前致谢

最佳答案

我用 Reflector 找到了这个异常的来源。在 ListPicker.cs 中,以下方法被覆盖。

protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)

在此方法中,如果设置了 SelectedItem 且 SelectedIndex 为 -1(除非它在加载之前设置),否则以下行将导致异常。如果未设置 SelectedItem,则永远不会到达此行(因此也不异常(exception))。

else if (!object.Equals(base.get_Items().get_Item(this.SelectedIndex), this.SelectedItem))

为了解决这个问题(直到他们解决这个问题)我有一些建议。

解决方法 1

如果您知道 TwoWay 绑定(bind)将生成的起始索引,那么您也可以设置 SelectedIndex 属性,TwoWay 绑定(bind)将起作用

<toolkit:ListPicker x:Name="WeekStartDay"
                    Header="Week begins on"
                    SelectedItem="{Binding Source={StaticResource AppSettings},
                                           Path=WeekBeginsSetting,
                                           Mode=TwoWay}"
                    SelectedIndex="1">
    <sys:String>monday</sys:String>
    <sys:String>sunday</sys:String>
</toolkit:ListPicker> 

解决方法 2

使用 Loaded 事件并从那里设置 Binding

<toolkit:ListPicker x:Name="WeekStartDay"
                    Header="Week begins on"
                    Loaded="WeekStartDay_Loaded">
    <sys:String>monday</sys:String>
    <sys:String>sunday</sys:String>
</toolkit:ListPicker>

private void WeekStartDay_Loaded(object sender, RoutedEventArgs e)
{
    Binding binding = new Binding();
    binding.Source = this.Resources["AppSettings"] as ApplicationSettings;
    binding.Path = new PropertyPath("WeekBeginsSetting");
    binding.Mode = BindingMode.TwoWay;
    WeekStartDay.SetBinding(ListPicker.SelectedItemProperty, binding);
}

关于c# - 双向绑定(bind)设置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4472486/

相关文章:

.Net DataBinding 具有值类型属性的新对象

c++ - 使用 XAML 和 C++ 再现本地视频文件

ASP.NET/Silverlight 控制 USB 设备

c# - 编辑时防止重复编辑/锁定数据库记录 - 单个后端服务器

c# - XAML 工具提示 + IsHitTestVisible ="False"

c# - 以编程方式启动按钮的弹出窗口

c# - 应用找不到位于另一个项目中的 Razor 页面

c# - 获取调用我的 dll 的 exe 的名称

c# - 连续的 XML 序列化原因 - EndRootElement 状态下的 token StartElement 将导致无效的 XML 文档

c# - 编辑评论框脚本为动态