是否可以在代码中访问DataTemplate中的项目?我的意思是,我在Window.Resources中定义了DataTemplate,如下所示:
<Window.Resources>
<DataTemplate x:Key="MyTemplate" DataType="MyType">
<StackPanel Orientation="Horizontal" Height="Auto" Tag="ColorString">
<Rectangle Width="16" Height="14" Margin="2,1" VerticalAlignment="Center" Stroke="Red">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Path=FillColor}"/>
</Rectangle.Fill>
</Rectangle>
<TextBlock VerticalAlignment="Center" Text="{Binding Path=Value}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
我需要在代码中设置Rectangle的一些属性。我怎样才能做到这一点?加载DataTemplate时,其VisualTree为null。
答案 0 :(得分:0)
您可以将Loaded事件添加到StackPanel和后面的代码中。
private void StackPanel_Loaded(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = sender as StackPanel;
Rectangle rectangle = GetVisualChild<Rectangle>(stackPanel) as Rectangle;
//..
}
这不会影响DataTemplate本身,但每次使用它时,都会调用StackPanel_Loaded。
GetVisualChild的实现..
public static T GetVisualChild<T>(object parent) where T : Visual
{
DependencyObject dependencyObject = parent as DependencyObject;
return InternalGetVisualChild<T>(dependencyObject);
}
private static T InternalGetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}