简体   繁体   English

如何在Windows Phone应用中获取选中的复选框内容?

[英]How to get checked checkbox content in windows phone app?

I am developing windows phone app .In app,I want to put multiple check box.I able to put multiple check box.But when i checked on check box i want getting its content(check box content).For that i am use checked event and also click event but i cant get result as i want.My xaml code is as below: 我正在开发Windows Phone应用程序。在应用程序中,我想放置多个复选框。我能够放置多个复选框。但是当我选中复选框时,我想要获取其内容(复选框内容)。为此,我使用了事件和单击事件,但我无法获得所需结果。我的xaml代码如下:

        <ListBox Name="hobbylist" ItemsSource="{Binding}" Margin="0,0,10,10" >

            <ListBox.ItemTemplate>

                <DataTemplate>

                    <StackPanel Orientation="Horizontal">

                        <CheckBox Name="hobbycheck" Content="{Binding Path=Title}"

                                  IsChecked="{Binding IsSelected}" ClickMode="Release" 

                Click="CheckBox_Click" ></CheckBox>
                    </StackPanel>

                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>

    </Grid>

Please help me ... 请帮我 ...

I think you are using the Checkbox not correctly according to its purpose. 我认为您没有按照目的正确使用Checkbox

Checkbox should represent a state (eg yes/no) regarding a subject. Checkbox应代表有关主题的状态(例如,是/否)。 Still, you just have to use the Checked event when the checkbox gets checked and Unchecked otherwise. 尽管如此,当复选框被选中时,您只需要使用Checked事件;否则,您可以使用Unchecked

So in the Checked event, get the content you wish. 因此,在Checked事件中,获取您想要的内容。

Edit 编辑

You have to maintain this with the MVVM pattern somehow. 您必须以某种方式使用MVVM模式来维护它。 For that, there are plenty of examples in the internet, I am sure you can handle that. 为此,互联网上有很多示例,我相信您可以解决。

Instead of having Click="CheckBox_Click" , use the Check event : 代替使用Click="CheckBox_Click" ,而使用Check事件:

private void CheckBox_Checked (Object sender, EventArgs e)
{
    var currentCheckBoxItem = sender as CheckBox;
    if (currentCheckBoxItem.IsChecked == true)
        {
             //you manipulation here...
        }
}

Still. 仍然。 this might just not work, because you haven't provided enough details of your matter. 这可能不起作用,因为您没有提供足够的详细信息。

Edit 2 A little of MVVM... 编辑2一点MVVM ...

First, make a Hobby model class, with a single string property (you might change your mind later to add more properties, Idk) : 首先,制作一个具有单个字符串属性的Hobby模型类(稍后可能会改变主意以添加更多属性Idk):

public class Hobby : INotifyPropertyChanged
{
    private string _name;
    public string Name 
    { 
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged(); 
        }
    }

    private bool _isSelected;
    public bool IsSelected 
    {
        get
        {
            return _isSelected;
        } 
        set
        {
            _isSelected = value;
            OnPropertyChanged();
        }
    }

    //You can add some multiple properties here (***)

    public Hobby (string hobbyName, bool isSelected)
    {
         Name = hobbyName;
         IsSelected = isSelected;
    }

    //INotifiyPropertyChanged interface member implementation ...
}

( * ) For example, a short description and then bind it on the View. *例如,简短说明,然后将其绑定到视图上。 The major advantage of this MVVM pattern is logic separation, so if something has to change, the separation of each component makes it easier. MVVM模式的主要优点是逻辑分离,因此,如果必须更改某些内容,则每个组件的分离将使其变得更容易。

Second, create a ViewModel class (you should implement INotifyPropertyChanged interface) : 其次,创建一个ViewModel类(您应该实现INotifyPropertyChanged接口):

public class HobbiesViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Hobby> _hobbies;

    public ObservableCollection<Hobby> HobbiesCollection
    {
         get 
         {
             return _hobbies;
         }
         set
         {
             _hobbies = value;
             OnPropertyChanged();
         }
    }

    //Constructor
    public HobbiesViewModel
    {
        HobbiesCollection = new ObservableCollection<Hobby>();
    }

    //INotifyPropertyChanged interface member implementation ...
}

Third, create an instance of the ViewModel (the ObservableCollection). 第三,创建ViewModel的实例(ObservableCollection)。 Use this quick help out : In the App.xaml.cs , create a static object and use it through the app as you need it : 使用此快速帮助:在App.xaml.cs ,创建一个静态对象,并根据需要在应用程序中使用它:

public partial class App
{

//This already exists in your app's code, but I've written it to
//make an idea where to write the Hobbies object
public static PhoneApplicationFrame RootFrame { get; private set; }

public static HobbiesViewModel Hobbies;

//Again, the already existing constructor
public App()
{
   ...

   Hobbies = new HobbiesViewModel();
}

Now, you almost have it all set; 现在,您已经准备就绪。 You have the Model, you have the ViewModel, all that's left is to create the connection with the View. 您有模型,有ViewModel,剩下的就是创建与View的连接。 This can be easily done through binding. 通过绑定可以很容易地做到这一点。 The ViewModel represents the DataContext of your control (in your case the LongListSelector , so in that View's (Page's) constructor, write the following statement : ViewModel代表控件的DataContext (在您的情况下为LongListSelector ,因此在该View的(Page的)构造函数中,编写以下语句:

yourListControlName.DataContext = App.Hobbies;

Now the binding is the only thing left. 现在,绑定是剩下的唯一内容。 This is done in XAML code. 这是在XAML代码中完成的。 I won't put a whole chunk of XAML code here, cause you know best how your control looks like. 我不会在这里放置一整块XAML代码,因为您最了解控件的外观。 Still, judging by the short sample you provided, there a few adjustments only : 不过,从您提供的简短示例来看,仅存在一些调整:

The items source of the list XAML control will be bound to the ObservableCollection object name of the ViewModel representing the control's DataContext . 列表XAML控件的项目源将绑定到表示控件的DataContextViewModelObservableCollection对象名称。 A bit fuzzy, huh? 有点模糊吧? To be clearer, in this case, you need to write ItemsSource="{Binding HobbiesCollection}" , the ObservableCollection . 为了更清楚,在这种情况下,您需要编写ItemsSource="{Binding HobbiesCollection}"ObservableCollection Also, in the template, you should have that CheckBox which is bound on your Model 's properties : 另外,在模板中,您应该具有绑定到Model属性的CheckBox

<DataTemplate>
    <StackPanel Orientation="Horizontal"> //StackPanel is kinda useless if you have
                                          //only one child control in it. But I wrote
                                          //according to your code.
        <Checkbox Content="{Binding Name}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
    </StackPanel>
</DataTemplate>

Now, here things are a bit unclear to me. 现在,这里的事情对我来说还不清楚。 Why would you use the Checkbox? 为什么要使用复选框? I've thought of the next possible scenario : You come with some string of your hobbies through deserialization of the Json Data. 我想到了下一个可能的场景:通过反序列化Json Data,您会产生一些兴趣爱好。 To add them to the ViewModel , you need only : 要将它们添加到ViewModel ,您只需要:

App.Hobbies.HobbiesCollection.Add(new Hobby("firstHobbyFromJson", true));
App.Hobbies.HobbiesCollection.Add(new Hobby("secondHobbyFromJson", true));

This would make all hobbies already selected in the View . 这将使“ View已经选择的所有爱好。 I guess, you would add some other hobbies, the user doesn't have which are not selected and could add them now : 我想,您可能会添加其他一些兴趣爱好,而用户没有这些兴趣爱好,因此现在可以添加它们:

App.Hobbies.HobbiesCollection.Add(new Hobby("aNewHobby", false));
App.Hobbies.HobbiesCollection.Add(new Hobby("anotherNewHobby", false));

At this point, the user has all its previous hobbies in the list and as well some new hobbies you provided him. 此时,用户将列表中以前的所有爱好以及您提供给他的一些新爱好。 After his selection is done, if you need to serialize the Json with only the selected hobbies, you could get like this : 完成他的选择后,如果只需要序列化所选兴趣爱好的Json,就可以这样:

var userHobbies = App.Hobbies.HobbiesCollection.Where(h => h.IsSelected);

or with a foreach and get only those hobby objects which have the IsSelected property as true . 或使用foreach并仅获取那些具有IsSelected属性为true爱好对象。

Good luck! 祝好运!

I found a Simpler solution. 我找到了一个更简单的解决方案。

My Model 我的模特

You need to use two variables otherwise you may get an 'stackoverflowexception' 您需要使用两个变量,否则可能会得到“ stackoverflowexception”

    public class ModelObj
    {
        public int position { set; get; }
        public bool isChecked
        {
            get { return IsChecked; }
            set { IsChecked = value; }
        }
        public bool IsChecked;
    }

Code to be added in xaml: 在xaml中添加的代码:

  1. isChecked in xaml sets the ListView Checkbox 在xaml中进行isChecked设置ListView复选框

  2. Mode=TwoWay updates the isChecked boolean value of the model class Mode = TwoWay更新模型类的isChecked布尔值

     <CheckBox IsChecked="{Binding isChecked , Mode=TwoWay}" Checked="checkBox_Checked" > 

c# Code that handles the event c#处理事件的代码

   private void checkBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (ModelObj obj in listItem)
        {
            if (obj.isChecked == true)
            {
                int selectedPosition = obj.position;
            }

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM