WPF DataGrid 之数据绑定--实例2
1.前台Grid定义
<!--数据绑定--> <DataGrid Grid.Row="1" Name="gridOne" Margin="10" ColumnWidth="150" AlternatingRowBackground="Linen" AutoGenerateColumns="False" > <DataGrid.Columns> <DataGridTextColumn Header="域名全称" Binding="{Binding HostName ,Mode=OneWay}"/> <DataGridTextColumn Header="IP地址" Binding="{Binding IP,Mode=OneWay}"></DataGridTextColumn> <DataGridCheckBoxColumn Header="是否启用" Binding="{Binding IsEnable,Mode=OneWay}" Width="80"> </DataGridCheckBoxColumn> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="删除" Width="100" Click="Button_Click_1" Uid="{Binding IP ,Mode=OneWay}" ContentStringFormat="{Binding HostName,Mode=OneWay}"> </Button> <!--Button 绑定显示内容--> <!--<Button Width="100" Click="Button_Click_1"> <Button.Content> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0}-{1}"> <Binding Path="IP"/> <Binding Path="HostName"/> </MultiBinding> </TextBlock.Text> </TextBlock> </Button.Content> </Button>--> <!--TextBox 绑定显示内容--> <!--<TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0}-{1}"> <Binding Path="IP"/> <Binding Path="HostName"/> </MultiBinding> </TextBlock.Text> </TextBlock>--> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
2.后台代码处理
HostsHelper _helper = new HostsHelper(); public MainWindow() { InitializeComponent(); //绑定列表 Rebind(); } //添加域名和IP绑定 private void Button_Click(object sender, RoutedEventArgs e) { string ip = txtIp.Text; string hostname = txtHostName.Text; if (string.IsNullOrEmpty(hostname)) { txtHostName.Focus(); ShowResult("请输入域名"); return; } if (string.IsNullOrEmpty(ip)) { txtIp.Focus(); ShowResult("请输入IP地址"); return; } //添加结果 _helper.Add(new HostData(true, ip, hostname)); MessageBox.Show("添加成功"); //重新绑定 Rebind(); } //重新绑定结果 public void Rebind() { gridOne.ItemsSource = _helper.HostDatas; gridOne.Items.Refresh(); } //显示结果 public void ShowResult(string str) { Result.Content = str; } //删除内容 private void Button_Click_1(object sender, RoutedEventArgs e) { Button btn = sender as Button; MessageBoxResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { _helper.Remove(new HostData(true,btn.Uid.ToString(),btn.ContentStringFormat.ToString())); Rebind(); } }