获取不到ItemControl的数据模板中的控件
我在ItemControl的数据模板中使用3个自定义控件,然后要在BackgroundWorker异步操作处理每个数据项里的控件的内容,代码如下:
这个是样式
<Style x:Key="GuestTilePanelStyle" TargetType="ItemsControl">
<Setter Property="xc:xTilePanel.ItemHeight" Value="30" />
<Setter Property="xc:xTilePanel.ItemWidth" Value="120" />
<Setter Property="ItemsControl.ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<xc:xTilePanel AnimatesNewItem="True" Attraction="2.0" Dampening="0.40" Variation="1.00" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsControl.ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="gProgressContainer" Height="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<xc:xSprocket x:Name="skProgress" Grid.Column="0" Width="30" Height="30" TickColor="#FF02AA1A" />
<xc:xShadePanel x:Name="spInfo" Grid.Column="1" HorizontalContentAlignment="Center" Transition="UpTransition" />
<xc:xIcoButton x:Name="btnCancel" Grid.Column="2" Width="20" xIconSize="16" xIcon="/Takewin.OS.Modularity.FePlat;component/Resources/i0001000000210003.png" />
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
private void SyncGuestToSource(int meetId)
{
this._Source.Add(meetId);
BackgroundWorker bg = new BackgroundWorker();
bg.WorkerReportsProgress = true;
bg.WorkerSupportsCancellation = true;
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.ProgressChanged += new ProgressChangedEventHandler(bg_ProgressChanged);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync(meetId);
}
private void bg_DoWork(object sender, DoWorkEventArgs e)
{
//会议ID在数据源中的索引位置
int index = this._Source.IndexOf(Convert.ToInt32(e.Argument));
e.Result = index;
string sql = string.Format("select * from TGuest where KMeetId={0}", e.Argument);
DataTable dtData = this._Dao.QueryDataSet(sql).Tables[0];
if (dtData != null && dtData.Rows.Count > 0)
{
foreach (DataRow dr in dtData.Rows)
{
((BackgroundWorker)sender).ReportProgress(index, dr["FName"]);
}
}
}
private void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int index = e.ProgressPercentage;
DependencyObject obj = (DependencyObject)this.itcSyncGuest.ItemContainerGenerator.ContainerFromIndex(index);
上面的obj获取到的对象是ContentPresenter类型的
ContentPresenter presenter = FindVisualChild<ContentPresenter>(obj);
DataTemplate dTemplate = presenter.ContentTemplate;
这里的dTemplate 一直获取到的是null,但是实际是有数据模板样式的
if (dTemplate != null)
{
xShadePanel sp = (xShadePanel)dTemplate.FindName("spInfo", presenter);
sp.Content = new TextBlock()
{
Text = Convert.ToString(e.UserState),
Foreground = Brushes.WhiteSmoke,
VerticalAlignment = VerticalAlignment.
Center,
HorizontalAlignment = HorizontalAlignment.Center
};
}
}
private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int index = Convert.ToInt32(e.Result);
this._Source.RemoveAt(index);
}