获取DataTemplate中控件的好方法是什么?我已经使用了处理感兴趣控件的Loaded事件的技巧,并且使用VisualTreeHelper来遍历视觉树,而这些都不是很优雅。访问DataTemplate控件的好方法是什么?以编程方式从DataTemplate访问控件
在一个示例中,我需要添加绑定whos ConverterParameter在设计时不知道,并且由于不支持绑定到ConverterParameters,所以我需要在代码中创建绑定。理想情况下,我希望能够在数据模板中的控件之外的Loaded事件处理程序之外执行此操作。
事实上,在这种情况下,处理事件根本不起作用,并导致出现OutOfMemoryException。这里是我的尝试:
generic.xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightTest">
<Style TargetType="local:TemplatedControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedControl">
<ListBox ItemsSource="{TemplateBinding ListBoxItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="SomeTextBlock"
Loaded="SomeTextBlock_Loaded"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
templatedcontrol.cs:
public class TemplatedControl : Control
{
public object ListBoxItemsSource
{
get { return (object)GetValue(ListBoxItemsSourceProperty); }
set { SetValue(ListBoxItemsSourceProperty, value); }
}
public static readonly DependencyProperty ListBoxItemsSourceProperty =
DependencyProperty.Register
("ListBoxItemsSource", typeof(object),
typeof(TemplatedControl), new PropertyMetadata(null));
public TemplatedControl()
{
this.DefaultStyleKey = typeof(TemplatedControl);
}
public void SomeTextBlock_Loaded(object sender, RoutedEventArgs ea)
{
}
}
请问您是否可以扩展这一点以包含一个可能有用的场景? – 2009-09-07 13:54:34
添加到问题... – 2009-09-09 20:14:40