我正在开发一个Windows Phone 8应用程序,其中,我正在使用列表框来显示多个详细信息。我的问题是,我想访问代码后面的数据模板,即我想访问完整的数据模板,访问所有在数据模板中声明的子模板。访问列表框的完整数据模式
只是我想改变列表框内的数据模板内的元素的可见性。请提出建议。
在此先感谢
我正在开发一个Windows Phone 8应用程序,其中,我正在使用列表框来显示多个详细信息。我的问题是,我想访问代码后面的数据模板,即我想访问完整的数据模板,访问所有在数据模板中声明的子模板。访问列表框的完整数据模式
只是我想改变列表框内的数据模板内的元素的可见性。请提出建议。
在此先感谢
这听起来像你想有一个DataTemplate
显示或隐藏基于它绑定到对象的属性某些元素。其中一个更好的方法来得到这个是做线沿线的东西:
class MyData
{
...
public string Email {get {...} set {...}}
...
}
既然可以在用户或可能不会有一个电子邮件地址,你的DataTemplate可以使用转换器的电子邮件的字符串值转换成Visibility
可用于显示或隐藏该字段的值。该转换器看起来是这样的:
public class StringNotNullToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = value as string;
if (!string.IsNullOrEmpty(text))
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
和你在XAML中的引用添加到它像:
<phone:PhoneApplicationPage.Resources>
<this:StringNotNullToVisibilityConverter x:Key="StringNotNullToVisibilityConverter"/>
</phone:PhoneApplicationPage.Resources>
最后你DataTemplate
将有一个看起来像一条线:
<TextBlock Text="{Binding Email}" Visibility="{Binding Email, Converter={StaticResource StringNotNullToVisibilityConverter}}"/>
本质上说“显示电子邮件,但如果电子邮件为空,则隐藏此字段”。
我发现了这个问题
public static T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
try
{
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 T)
{
return (T)child;
}
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
一个解决方案,我用这个方法来找出我的数据模板中的第一元素,然后我改变了元素的可见性。 这里是一个示例如何使用这种方法..
ListBoxItem item = this.lstboxMedicationList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
CheckBox tagregCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
tagregCheckBox.Visibility = Visibility.Visible;
lstboxMedicationList.UpdateLayout();
here i is the index of ListBox item.
为什么要更新DataTemplate这种方式?它不会更改您已经可以看到的当前创建的列表项目。它期望你实际上想单独绑定/更新每个列表项。 –