[英]set checkbox in a combox to checked wpf
我创建了一个自定义的wpf控件-本质上是带有复选框的combox。 combox全部成功绑定到项目列表。
这是我的xaml代码。
<ComboBox Height="28" HorizontalAlignment="Left" Margin="106,7,0,0" Name="comboBox1" VerticalAlignment="Top" Width="174" ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="ckabc" Content="{Binding}" CommandParameter="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我的代码是这样的:
private List<string> names;
public List<string> Names
{
get { return names; }
set
{
names = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Names"));
}
}
Names = new List<string> { "Sensor Not Connected", "Poor Signal Quality", "Excessive Light", "PreAmp Not Connected", "Replace Sensor", "Interference Detected", "Sensor Unusable", "Sensor Change" };
this.OnPropertyChanged(new PropertyChangedEventArgs("Names"));
我为每个列表项创建了属性:
public string SensorNotConnected
{
get
{
return Names.ElementAt(0);
}
set
{
this.emuObj.SensorNotConnected(Convert.ToBoolean(value), channelIndex);
}
}
以相同的方式为其他列表项创建属性。 我的想法是绑定复选框的Ischecked属性并进行迭代。 但是我该怎么做。 用户可以选择一个复选框或多个复选框。 请为此提供一些答案。
PS:我正在使用MVVM模型。
这是一个如何解决此问题的简单演示。 该解决方案使用Mvvm Light ,但这不是必需的。 您可以创建一个类(该类具有可绑定的bool IsChecked属性),而不仅仅是一个List<string>
,而可以创建一个类(在本示例中为“ Name”)。 参见<CheckBox Grid.Column="1" Name="ckabc" IsChecked="{Binding IsChecked}"/>
,这是我们绑定IsChecked属性的地方。
<Window x:Class="CustomControlWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
<Grid>
<ComboBox Height="28" HorizontalAlignment="Left" Margin="106,7,0,0" VerticalAlignment="Top" Width="174" ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions>
<TextBlock Text="{Binding Description}"></TextBlock>
<CheckBox Grid.Column="1" Name="ckabc" IsChecked="{Binding IsChecked}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
public class Name
{
public string Description { get; set; }
public bool IsChecked { get; set; }
}
}
视图模型:
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Names = new List<Name>() { new Name { Description = "Name1", IsChecked = false }, new Name { Description = "Name2", IsChecked = false } };
}
private List<Name> _names;
public List<Name> Names
{
get { return _names; }
set
{
_names = value;
RaisePropertyChanged(() => Names);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.