我正试图从复选框中获取已检查的号码。
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApplication6"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:Test x:Key="TestContext"></local:Test>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding TestList}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding number}" Command="{Binding WhatChecked,Source={StaticResource TestContext},Mode=OneWay}" IsChecked="{Binding check}" CommandParameter="{Binding check}"></CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
但我只能传递一个参数
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public class DataStruct
{
public string number {get;set;}
public bool check {get;set;}
}
public class Test
{
public Test()
{
WhatChecked = new RelayCommand<bool>((e) => Show(e));
DataStruct DS = new DataStruct();
DS.check = false;
DS.number = "101";
DataStruct DS1 = new DataStruct();
DS1.check = false;
DS1.number = "102";
DataStruct DS2 = new DataStruct();
DS2.check = false;
DS2.number = "103";
testList = new List<DataStruct>();
TestList.Add(DS);
TestList.Add(DS1);
TestList.Add(DS2);
}
public ICommand WhatChecked { get; set; }
private List<DataStruct> testList;
public List<DataStruct> TestList
{
get { return testList; }
set { testList = value; }
}
private void Show(object param)
{
if (Convert.ToBoolean(param))
{
Debug.WriteLine("Clicked: {0}", param);
}
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Test();
}
}
}
但我不能将带有数字的字符串传递给命令参数,因为我已经有参数。
答案 0 :(得分:1)
由于所有项目都在列表中,并且所有项目都绑定到复选框IsChecked
属性,因此您只需使用LINQ搜索列表
TestList.Where(p=>p.check).Count();
答案 1 :(得分:0)
如果将CommandParameter绑定设置为{Binding},那么它将传递CheckBox的DataContext(即整个DataStruct对象)作为参数。这应该允许您访问所有DataStruct属性,而不仅仅是检查。请注意,许多人认为这违反了MVVM原则,因为ViewModel变得更紧密地依赖于View /依赖于View。我已经使用过这种方法几次,我认为有必要完成工作。
<CheckBox Content="{Binding number}" Command="{Binding WhatChecked,Source={StaticResource TestContext},Mode=OneWay}" IsChecked="{Binding check}" CommandParameter="{Binding}"></CheckBox>