Windows phone 7 访问Listbox数据模板内的控件
我正在开发一个Windows Phone 8,我有一个单一的选择列表框和这个Windows phone 7 访问Listbox数据模板内的控件,windows-phone-7,windows-phone-8,listbox,Windows Phone 7,Windows Phone 8,Listbox,我正在开发一个Windows Phone 8,我有一个单一的选择列表框和这个数据模板: <DataTemplate x:Key="LocalizationItemTemplate"> <Border BorderBrush="Black" BorderThickness="2" CornerRadius="8" Background="#FF003847" Height="80"> <Grid x:Name="contentGrid" Mar
数据模板
:
<DataTemplate x:Key="LocalizationItemTemplate">
<Border BorderBrush="Black" BorderThickness="2" CornerRadius="8" Background="#FF003847" Height="80">
<Grid x:Name="contentGrid" Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="90*"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="selectedCheck" Content="CheckBox" HorizontalAlignment="Center" Height="20" Margin="0" VerticalAlignment="Center" Width="20"/>
<TextBlock x:Name="locationName" TextWrapping="Wrap" Text="{Binding Name}" Margin="10,34,0,34" VerticalAlignment="Center" FontSize="24" Grid.ColumnSpan="2" Height="0"/>
</Grid>
</Border>
</DataTemplate>
如何以编程方式访问
selectedCheck
复选框?这就是使用MVVM的原因。您可以将listbox绑定到一组Location对象,并将Location.Selected绑定到复选框。在ViewModel中,您可以轻松找到用户选择的任何内容并继续。在可视化树中没有乱七八糟的东西。你没有对复选框应用绑定吗?浏览VisualTree会很枯燥。我认为正确的答案是将绑定应用于复选框。由于糟糕的编程风格,这肯定是一个枯燥的过程。但你做得很好。
private T FindElementInVisualTree<T>(DependencyObject parentElement, string name) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is FrameworkElement && (child as FrameworkElement).Name.Equals(name))
{
return (T)child;
}
else
{
var result = FindElementInVisualTree<T>(child, name);
if (result != null)
return result;
}
}
return null;
}
ListBoxItem item = list.ItemContainerGenerator.ContainerFromItem(list.SelectedItem) as ListBoxItem;
CheckBox check = FindElementInVisualTree<CheckBox>(item, "selectedCheck");
<CheckBox x:Name="selectedCheck" IsChecked={Binding Checked, Mode=TwoWay} ...