WPF的DataGrid真的很强大,可以显示子行内容,里面可以是任意控件,这里我做了个一个简单的DataGrid,双击某一行,打开里面的TextBox,并显示绑定内容,废话不说,直接代码
界面:
<Window x:Class="WpfApplication1.Window21"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window21" Height="300" Width="300">
<Grid>
<DataGrid Name="dataGrid1" ItemsSource="{Binding}">
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock Name="innerGrid"></TextBlock>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
</Window>
后台代码:
/// <summary>
/// Window21.xaml 的交互逻辑
/// </summary>
public partial class Window21 : Window
{
DataTable dt = new DataTable();
public Window21()
{
InitializeComponent();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("标题", typeof(string));
dt.Columns.Add("内容", typeof(string));
dt.Columns.Add("iscp", typeof(bool));
dt.Rows.Add("1", "情歌", "情歌是简述一个美好的爱情故事", false);
dt.Rows.Add("2", "What Are Words", "讲述一个不离不弃的爱情故事", false);
this.dataGrid1.DataContext = dt;
this.dataGrid1.IsReadOnly = true;
this.dataGrid1.MouseDoubleClick += new MouseButtonEventHandler(dataGrid1_MouseDoubleClick);
this.dataGrid1.RowDetailsVisibilityChanged += new EventHandler<DataGridRowDetailsEventArgs>(dataGrid1_RowDetailsVisibilityChanged);
}
void dataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DataGridRow row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(this.dataGrid1.SelectedIndex);
DataRowView rowview = this.dataGrid1.SelectedItem as DataRowView;
if (Convert.ToBoolean(rowview["iscp"]) == false)
{
rowview["iscp"] = true;
row.DetailsVisibility = System.Windows.Visibility.Visible;
}
else
{
rowview["iscp"] = false;
row.DetailsVisibility = System.Windows.Visibility.Collapsed;
}
}
void dataGrid1_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
{
DataGridRow row = e.Row;
TextBlock inne = e.DetailsElement as TextBlock;
System.Data.DataRowView rowview = row.Item as System.Data.DataRowView;
if (Convert.ToBoolean(rowview["iscp"]))
{
row.DetailsVisibility = System.Windows.Visibility.Visible;
string value = rowview["内容"].ToString();
inne.Height = 100;
inne.Text = value;
}
else
{
row.DetailsVisibility = System.Windows.Visibility.Collapsed;
}
}
}
}
代码比较简单,我就不说明了,看不懂的再留言问我吧.
这东西看简单,其实真的还是用了很多自己的时间,转载的童鞋,记得保留我的连接http://www.cnblogs.com/linyijia/archive/2013/03/15/2961102.html,不做纯粹的伸手党哦!