C# 查找DataTemplate生成的元素
我正在更改listbox的TextBlock元素的IsEnabled属性,如下所示C# 查找DataTemplate生成的元素,c#,wpf,C#,Wpf,我正在更改listbox的TextBlock元素的IsEnabled属性,如下所示 <ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemsSource> <Binding Source="{StaticResource Invent
<ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
IsSynchronizedWithCurrentItem="True">
<ListBox.ItemsSource>
<Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
</ListBox.ItemsSource>
</ListBox>
列表框使用以下数据模板作为
<DataTemplate x:Key="myDataTemplate">
<TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
//获取当前选定的ListBoxItem
//请注意,列表框必须具有
//IsSynchronizedWithCurrentItem设置为True以使其工作
ListBoxItem myListBoxItem=
(ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
//获取myListBoxItem的ContentPresenter
ContentPresenter myContentPresenter=FindVisualChild(myListBoxItem);
//从在该ContentPresenter上设置的DataTemplate中查找textBlock
DataTemplate myDataTemplate=myContentPresenter.ContentTemplate;
TextBlock myTextBlock=(TextBlock)myDataTemplate.FindName(“TextBlock”,myContentPresenter);
//对DataTemplate生成的TextBlock执行某些操作
myTextBlock.IsEnabled=false;
私有子项FindVisualChild(DependencyObject obj)
where-childItem:DependencyObject
{
for(int i=0;i
但是如何设置
isEnabled=false编码>该列表框中的所有文本块?只需使用foreach循环遍历列表框中的所有项,并执行与对一个项执行的相同操作
foreach (ListBoxItem item in yourListBox.Items)
{
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(item );
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
myTextBlock.IsEnabled=false;
}
只需使用foreach循环遍历列表框的所有项,并对一个项执行相同的操作
foreach (ListBoxItem item in yourListBox.Items)
{
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(item );
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
myTextBlock.IsEnabled=false;
}
不要那样做。如果存在虚拟化,则某些项目的容器甚至不存在,您将需要处理相当混乱的代码来解决该问题。尝试绑定IsEnabled
,并相应地设置property/XML属性。不要这样做。如果存在虚拟化,则某些项目的容器甚至不存在,您将需要处理相当混乱的代码来解决该问题。尝试绑定IsEnabled
,并相应地设置property/XML属性
<TextBlock Name="textBlock" IsEnabled="{Binding path=SomeBoolProperty"} FontSize="14" Foreground="Blue">