我有一个组合框,复选框内有复选框。我想要多选复选框的值。我的代码:
<ComboBox Name="LocationFilterComboBox" Width="100" SelectedItem="{Binding LocationValue}">
<ComboBox.ItemTemplate >
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox Content="{Binding LocationValue}" IsChecked="{Binding ElementName=all, Path=IsChecked, Mode=TwoWay}" Width="120" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
后端代码:
//code to get the value
public partial class Location
{
#region Property
private string LOCAID;
public string LocaId
{
get
{
return LOCAID;
}
set
{
value = LOCAID;
}
}
private string LOCADESC;
public string LocationValue
{
get
{
return LOCADESC;
}
set
{
value = LOCADESC;
}
}
#endregion
}
}
//code for binding the location
public IList<Location> BindAllLocation()
{
if (Repository != null) Repository.Dispose();
Repository = GetInvoiceRepository();
IList<Location> locationList = Repository.GetLocations(((App)Application.Current).DataContextFactory);
return locationList;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LocationFilterComboBox.ItemsSource = BindAllLocation();
}
答案 0 :(得分:1)
我不会直接设置ItemsSource。尝试绑定它:
private ObservableCollection<Location> _locationList = new ObservableCollection<Location>();
public ObservableCollection<Location> LocationList
{
get { return _locationList; };
set
{
if (_locationList == value)
return;
_locationList = value;
OnPropertyChanged();
}
private Location _currentLocation;
public Location CurrentLocation
{
get { return _currentLocation; };
set
{
if (_currentLocation == value)
return;
_currentLocation = value;
OnPropertyChanged();
}
public IList BindAllLocation()
{
if (Repository != null) Repository.Dispose();
Repository = GetInvoiceRepository();
IList<Location> locationList = Repository.GetLocations(((App)Application.Current).DataContextFactory);
return locationList;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var item in BindAllLocation())
LocationList.Add(item);
}
在Xaml中:
<ComboBox ItemsSource="{Binding *binding to LocationList*}" Width="100" SelectedItem="{Binding CurrentLocation}">
<ComboBox.ItemTemplate >
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox Content="{Binding LocationValue}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Width="120" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我不知道ComboBox上的DataContext,所以如果您遇到问题请尝试this。
然后您可以使用以下方法对所选值进行排序:
var result = LocationList.Where(x => x.IsChecked);
当然,你必须有一个IsChecked属性。
答案 1 :(得分:0)
由于IsChecked
中每个CheckBox
的{{1}}属性都绑定到“全部”ComboBox
的{{1}}属性,因此您应该能够直接从这个获得价值:
IsChecked
否则另一个选项是将CheckBox
属性添加到bool isChecked = all.IsChecked;
类并绑定到此类:
bool
然后,您可以通过简单地迭代Location
来获取<CheckBox Content="{Binding LocationValue}" IsChecked="{Binding IsChecked}" Width="120" />
中每个人CheckBox
的价值:
ComboBox