关于wpf,datagrid,双向数据绑定用法
定义一个数据绑定的datagrid,用来呈现数据,其中第二列是模板列,要求可以双向绑定
checkbox
<DataGrid x:Name="dataGrid" Grid.Row="0" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="AA" Binding="{Binding AA,Mode=TwoWay}" />
<DataGridTemplateColumn Header="BB">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding BB, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
wpf 双向绑定
ObservableCollection<class1> bindingData = new ObservableCollection<class1>();
public class class1
{
public string AA{get;set;}
public bool BB { get; set; }
}
public void InitDataBinding()
{
class1 a = new class1();
a.AA = "aaaaa";
a.BB = true;
bindingData.Add(a);
}
//绑定,初始化
dataGrid.ItemsSource = bindingData;
<StackPanel>
<TextBlock x:Name="ShowBBValue" Text="{Binding BB}" />
<DataGrid x:Name="dataGrid" Grid.Row="0" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="AA" Binding="{Binding AA,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<DataGridTemplateColumn Header="BB">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding BB, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
public partial class MainWindow : Window
{
class1 a = new class1();
ObservableCollection<class1> bindingData = new ObservableCollection<class1>();
public MainWindow()
{
InitializeComponent();
InitDataBinding();
}
void InitDataBinding()
{
a.AA = "aaaaa";
a.BB = true;
bindingData.Add(a);
ShowBBValue.DataContext = this.a;
dataGrid.ItemsSource = bindingData;
}
}
public class class1 : INotifyPropertyChanged
{
private bool _bb;
private string _aa;
public string AA
{
get { return _aa; }
set { this._aa= value; OnPropertyChanged("AA"); }
}
public bool BB
{
get { return this._bb; }
set
{
this._bb= value;
OnPropertyChanged("BB");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}