gpt4 book ai didi

c# - 如何获取内容控件中的元素

转载 作者:行者123 更新时间:2023-11-30 20:00:55 27 4
gpt4 key购买 nike

我需要在内容控件中找到元素:

<ContentControl Content="{Binding YourChoices}" Grid.ColumnSpan="3" x:Name="ccBloodGroup">
<ContentControl.ContentTemplate>
<DataTemplate>
<Grid>
<ComboBox x:Name="cbBloodGroup" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="10,160,0,0" VerticalAlignment="Top" Width="331" Height="45">
<ComboBoxItem>A+</ComboBoxItem>
<ComboBoxItem>A-</ComboBoxItem>
<ComboBoxItem>B+</ComboBoxItem>
<ComboBoxItem>B-</ComboBoxItem>
<ComboBoxItem>O+</ComboBoxItem>
<ComboBoxItem>O-</ComboBoxItem>
<ComboBoxItem>AB+</ComboBoxItem>
<ComboBoxItem>AB-</ComboBoxItem>
</ComboBox>
<TextBlock x:Name="tb" Text=" Blood Type" IsHitTestVisible="False" Visibility="Hidden" HorizontalAlignment="Left" Margin="10,176,0,0" VerticalAlignment="Top"/>
</Grid>
<DataTemplate.Triggers>
<Trigger SourceName="cbBloodGroup" Property="SelectedItem" Value="{x:Null}">
<Setter TargetName="tb" Property="Visibility" Value="Visible"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>

我在网上找到了答案

 ComboBox cb = ccBloodGroup.ContentTemplate.FindName("cbBloodGroup", ccBloodGroup) as ComboBox;

但这给了我一个运行时异常,提示“此操作仅对应用了此模板的元素有效。”

请帮忙..

最佳答案

此方法将帮助您:

public T FindElementByName<T>(FrameworkElement element, string sChildName) where T : FrameworkElement
{
T childElement = null;
var nChildCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < nChildCount; i++)
{
FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;

if (child == null)
continue;

if (child is T && child.Name.Equals(sChildName))
{
childElement = (T)child;
break;
}

childElement = FindElementByName<T>(child, sChildName);

if (childElement != null)
break;
}
return childElement;
}

然后,我如何使用它,只需添加按钮,然后在按钮上单击:

 private void Button_OnClick(object sender, RoutedEventArgs e)
{
var element = FindElementByName<ComboBox>(ccBloodGroup, "cbBloodGroup");
}

关于c# - 如何获取内容控件中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19904989/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com