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

标签 c# .net 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"
    

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

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

我在想也许有某种方法可以从“SelectionChangedEventArgs”或“RoutedEventArgs”中获取事件的“来源”(例如“代码”或“用户输入”)......但也许不是?

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

我希望我能解释清楚 - 我以前从未在这里发过帖!

如果您能提供任何帮助,我将不胜感激。谢谢!

更新 - 感谢@MyKuLLSKI 的回答,这给了我一个工作的好地方。

作为旁注,基于这个想法,我尝试将它们最初保留为“List”,并将“IgnoreSelectionChanged”作为一个 int 来“倒计时”(因此在设置 ListPicker 的 ItemSource 之前,我设置了“IgnoreSelectionChanged+ =2”(考虑到将被触发的两个事件);类似地,我在手动设置 SelectedIndex 之前设置了“IgnoreSelectionChanged++”……这似乎也有效。

但是,使用绑定(bind)到 ListPicker 的“ObservableCollection”并依靠它来告知更改似乎比使用 ListPicker 自己的“SelectionChanged”事件更好,因此我将修改我的代码以改为使用它。

再次感谢!

最佳答案

我会尽量回答你所有的问题/问题

  1. 您在 XAML 中设置 ItemSource 时遇到问题的原因是因为我几乎可以肯定您遇到了一些绑定(bind)问题。要使绑定(bind)正常工作,您需要在 UIElement 上具有 DataContext 和绑定(bind)。

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

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

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

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

  6. Silverlight 缺少 IsLoaded 属性,因此您可能希望在页面加载为真时添加一个 bool 值。

  7. 当绑定(bind)不更改 UIElement 中的属性时。而是更改其绑定(bind)到的属性。

以下是我的解决方案,应该可以解决您的所有问题 (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>

代码隐藏

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--;
        }
    }
}

有很多,但应该有帮助

关于c# - WP7 工具包 - 当通过代码(不是用户输入)更改时,如何忽略 ListPicker 的 "SelectionChanged"和 ToggleSwitch 的 "Checked"事件等事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830588/

相关文章:

c# - DeviceNetworkInformation.IsCellularDataEnabled 始终返回 false

silverlight - 在线语音聊天 : Why client-server model vs. 点对点模式?

c# - 如何使用 C#8 IAsyncEnumerable<T> 异步枚举并行运行的任务

c# - 试图继承三个基类而不能

c# - Mac OS X Lion 上的屏幕捕获程序,最好在其他操作系统上可移植

c# - 我可以将这三个相似的函数合并为一个函数吗?

c# - 通过 Web 服务自动公开数据库表

c# - 中继器控件中的单选按钮列表

c# - ASP.NET WEB API 引用类型不会自动绑定(bind)

silverlight - 新的 Silverlight 应用程序不会生成 XAP