【发布时间】:2016-07-13 01:26:14
【问题描述】:
我有一个包含 3 列(文本框列、组合框列、复选框列)的数据网格,我想触发一个事件 当在组合框列中选择一个值时,将相应地更改复选框列的值。
(我不希望它按照代码编写的方式工作,我根本不知道该怎么做..)
例如在此代码中,当在组合框列中选择低于 90 的等级时(绑定到 Grade 属性)我想要复选框列的值(绑定到 GoodStudent property) 更改为false,当其高于 90 时,更改为true。
如果可能的话,不用额外的按钮。
谢谢。
ViewModel 类:
public class Student : INotifyPropertyChanged
{
public ObservableCollection<int> Grades { get; set; }
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
private int _Grade;
public int Grade
{
get
{
return _Grade;
}
set
{
_Grade = value;
OnPropertyChanged(new PropertyChangedEventArgs("Grade"));
}
}
private bool _GoodStudent;
public bool GoodStudent
{
get
{
return _GoodStudent;
}
set
{
_GoodStudent = value;
OnPropertyChanged(new PropertyChangedEventArgs("GoodStudent"));
}
}
public Student(string name, int g)
{
Grades = new ObservableCollection<int> { 30, 40, 90, 100 };
this.Name = name;
this.Grade = g;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
}
class ViewModel
{
public ObservableCollection<Student> Students { get; set; }
public ViewModel()
{
Students = new ObservableCollection<Student>
{
new Student("Dan",80),
new Student("Micheal",90)
};
}
}
XAML:
<Grid>
<DataGrid ItemsSource="{Binding Students}" AutoGenerateColumns="False" Margin="69,50,47,66">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Names"/>
<DataGridComboBoxColumn SelectedValueBinding="{Binding Grade, UpdateSourceTrigger=PropertyChanged}" Header="Grades" Width="80">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Grades, Mode=TwoWay , UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
<DataGridCheckBoxColumn Binding="{Binding GoodStudent, UpdateSourceTrigger=PropertyChanged}" Header="IsGood" />
</DataGrid.Columns>
</DataGrid>
</Grid>
【问题讨论】:
-
似乎你几乎拥有它(尽管你可以使用 DataTrigger 而不是计算属性),如果你想让你的复选框绑定正确(使用真实的属性名称)并设置“GoodStudent”等级被改变了。我们缺少什么?
-
将 goodStudent 中的
OnPropertyChanged(new PropertyChangedEventArgs("Grade"));更改为OnPropertyChanged(new PropertyChangedEventArgs("GoodStudent")); -
感谢您的 cmets,我现在更改了它,但是当我将高于 90 的等级插入
ComboBoxColumn时,它仍然不会更改CheckBoxColumn的值,我想要该值CheckBoxColumn 的值在其较高时自动设置为true。