WP7工具包 - 当代码更改(非用户输入)时,如何忽略ListPicker的"SelectionChanged"和ToggleSwitch的"Checked"事件等事件?

Cyb*_*Dog 5 .net c# silverlight xaml windows-phone-7

我是XAML和C#的新手,但在我玩过它的几周内一直很喜欢使用它.我已经开始在一个应用程序上工作,并在XAML中组合了一个简单的"设置"页面; 现在我正在尝试将事件连接到控件以(a)在用户与它们交互时更新应用程序状态,以及(b)在访问页面时具有当前状态.

我打了两个(相关的)路障但是:

  • 工具包:当我在XAML中定义"ListPickerItem"时,ListPicker控件似乎不能正常工作,所以在SettingsPage构造函数中,我手动设置了内容:

    lpColour.ItemsSource = new List<string>()
    {
        "Red","Blue","Green","Custom…"
    };
    lpColour.SelectedIndex = 1;  // set the currently selected item to "Blue"
    
    Run Code Online (Sandbox Code Playgroud)

    但是,因为控件(在此示例中为lpColour)在SelectionChanged上有一个事件,所以会触发两个事件(一个选中"红色"作为框填充,然后另一个选择"蓝色").我现在不想处理"SelectionChanged"; 只有当用户自己与控件交互时(例如,如果他们选择"自定义..."),我可以显示一个单独的文本框并给出焦点;但我不想在我设置时这样做页面,他们之前选择了"自定义...",否则用户在打开"设置"页面时会立即显示键盘...)

  • 同样,我发现当"IsChecked"属性更改为新的时,ToggleSwitch控件将触发"已检查"和"未检查"事件.同样,有没有办法在代码更改时忽略或抑制此事件?(我现在通过使用"Clicked"来解决这个问题,但从学习的角度来看,知道如何处理它会很好.)

我想也许有一些方法可以从"SelectionChangedEventArgs"或"RoutedEventArgs"获得事件的"起源"(例如"代码"或"用户输入")......但也许不是?

我还尝试设置一个"初始化"bool值(默认情况下为"false",运行构造函数后设置为"true",并将事件处理代码包装为"if(initialized){...}";但是在构造函数完成"lpColour.ItemSource = ..."和"lpColour.SelectedIndex = 1"代码完成时,"初始化"为"假"时,事件似乎仍然被触发.非常奇怪.:P

我希望我能清楚地解释一下 - 我以前从未在这里发布过!

我很感激您提供的任何帮助.谢谢!

更新 - 感谢@ MyKuLLSKI的回答,这给了我一个很棒的工作场所.

作为旁注,在这个想法的基础上,我尝试将它们保持为'List',并将"IgnoreSelectionChanged"作为一个"倒计时"的int(所以在设置ListPicker的ItemSource之前,我设置"IgnoreSelectionChanged + = 2" (考虑将被解雇的两个事件);类似地,我在手动设置SelectedIndex之前设置"IgnoreSelectionChanged ++"......这似乎也有效.

但是,使用绑定到ListPicker的"ObservableCollection"并依赖它来表示更改似乎比使用ListPicker自己的"SelectionChanged"事件更好,所以我将修改我的代码以使用它.

再次感谢!

MyK*_*SKI 6

我会尽力回答你所有的问题

  1. 你在XAML中设置ItemSource的原因是因为我几乎可以肯定你有一些Binding问题.要使Bindings工作,您需要在UIElement上使用DataContext和Binding.

  2. 购买属性的东西必须是DependencyProperty或INotifyPropertyChanged

  3. List也不是一个很好的Collection类型来绑定ListPicker.相反,您可能希望使用ObservableCollextion()代替.如果此集合绑定到ListPicker并且项目更改,则ListPicker将自动更新.

  4. SelectionChanged事件被触发2次的原因是因为你将它更改了两次.首次创建ListPicker时,Selected项为null或-1,因为其中没有项.然后,当您设置ItemSource时,它会自动将SelectedIndex更改为0,然后将其更改为1.

  5. 一种方法是每当您知道更改代码变量的用户时添加标记

  6. Silverlight缺少IsLoaded属性,所以你想在页面加载为true时添加一个bool.

  7. 当Binding不更改UIElement中的属性时.而是更改其绑定的属性.

以下是我的解决方案,应解决您的所有问题(WP7.1):

XAML

  <phone:PhoneApplicationPage 
       x:Class="WP7Sandbox.MainPage"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
       xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
       DataContext="{Binding RelativeSource={RelativeSource Self}}"
       mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
       FontFamily="{StaticResource PhoneFontFamilyNormal}"
       FontSize="{StaticResource PhoneFontSizeNormal}"
       Foreground="{StaticResource PhoneForegroundBrush}"
       SupportedOrientations="Portrait" Orientation="Portrait"
       shell:SystemTray.IsVisible="True"
       Loaded="PhoneApplicationPageLoaded">

    <Grid>
        <StackPanel>
            <toolkit:ListPicker ItemsSource="{Binding ListPickerCollection, Mode=TwoWay}" SelectionChanged="ListPickerSelectionChanged" SelectedIndex="{Binding ListPickerSelectedIndex, Mode=TwoWay}"/>
            <Button Click="ButtonClick" Content="Selection Change and Ignore Event"/>
            <Button Click="Button2Click" Content="Selection Change and Trigger Event"/>

            <toolkit:ToggleSwitch IsChecked="{Binding ToggleSwitchValue, Mode=TwoWay}"/>
        </StackPanel>
    </Grid>
</phone:PhoneApplicationPage>
Run Code Online (Sandbox Code Playgroud)

代码背后

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;

namespace WP7Sandbox
{
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }

        private bool IsLoaded;

        private bool IgnoreSelectionChanged;

        public ObservableCollection<string> ListPickerCollection { get; private set; }

        private bool _ToggleSwitchValue;
        public bool ToggleSwitchValue
        {
            get
            {
                 return _ToggleSwitchValue;
            }

            set
            {

                _ToggleSwitchValue = value;
                OnPropertyChanged("ToggleSwitchValue");
            }
        }

        private int _ListPickerSelectedIndex;
        public int ListPickerSelectedIndex
        {
            get
            {
                return _ListPickerSelectedIndex;
            } 

            set
            {
                _ListPickerSelectedIndex = value;
                OnPropertyChanged("ListPickerSelectedIndex");
            }
        }

        public MainPage()
        {
            InitializeComponent();

            ListPickerCollection = new ObservableCollection<string>()
            {
                "Red",
                "Blue",
                "Green",
                "Custom…"
            };
        }

        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            IsLoaded = true;
        }

        private void ListPickerSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsLoaded && !IgnoreSelectionChanged)
            {
            }

            IgnoreSelectionChanged = false;
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            // I want to ignore this SelectionChanged Event
            IgnoreSelectionChanged = true;
            ChangeListPickerSelectedIndex();
        }

        private void Button2Click(object sender, RoutedEventArgs e)
        {
            // I want to trigger this SelectionChanged Event
            IgnoreSelectionChanged = false; // Not needed just showing you
            ChangeListPickerSelectedIndex();
        }

        private void ChangeListPickerSelectedIndex()
        {
            if (ListPickerSelectedIndex - 1 < 0)
                ListPickerSelectedIndex = ListPickerCollection.Count - 1;

            else
                ListPickerSelectedIndex--;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有很多,但它应该有所帮助