WP7:有条件地显示&隐藏数据模板中的控制元素 [英] WP7: Conditionally show & hide control elements in Data Templates
问题描述
我有一个带有 ListBox 控件的笔记应用程序,它列出了 ObservableCollection
.class Note
有像
I have a note application with a ListBox control, which lists all the available notes from the ObservableCollection<Note> Notes
. class Note
has attributes like
String Title;
bool Has_Reminder;
DateTime Reminder_Date;
我想要的是显示 Reminder_Date
的 TextBlock 元素仅在 Has_Reminder
为真时显示.但我不知道如何从我的自定义控件 NoteListItem 访问此属性.它的 this.DataContext
属性为 null
,但该控件仍正确显示由 ListBox ItemsSource 传递的 Note 的绑定属性.我怎样才能做到这一点?
What I want is that the TextBlock element, which shows the Reminder_Date
, is only shown, if Has_Reminder
is true. But I do not know how to access this attribute from my custom control NoteListItem. Its this.DataContext
attribute is null
, but the control still properly displays the Note's bound attributes handed down by the ListBox ItemsSource. How can I achieve that?
感谢您的帮助.
我试图读取构造函数中的属性,但没有用:
public NoteListItem()
{
InitializeComponent();
Note this_note = LayoutRoot.DataContext as Note; // turns out, this_note is null
if (!this_note.Has_Reminder)
Reminder_Info.Visibility = System.Windows.Visibility.Collapsed;
}
NoteListItem 控件
<Grid x:Name="LayoutRoot" >
<TextBlock x:Name="Title" Text="{Binding Title}" />
<TextBlock x:Name="Reminder_Date" Text="{Binding Reminder_Date}" />
</Grid>
NoteList 控件:
<ListBox x:Name="NoteListBox" ItemsSource="{Binding Notes}" >
<ListBox.ItemTemplate>
<DataTemplate>
<local:NoteListItem />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
推荐答案
你知道如何使用转换器吗?您的转换器会将 bool 转换为 Visibility,然后您可以将 TextBlock 的 Visibility 绑定到 Has_Reminder
:
Do you know how to use a converter? Your converter would convert a bool to a Visibility, then you can bind the TextBlock's Visibility to Has_Reminder
:
<TextBlock x:Name="Reminder_Date" Text="{Binding Reminder_Date}" Visibility="{Binding Has_Reminder, Converter={...}}"/>
这可能有帮助:http://www.jeff.wilcox.name/2008/07/visibility-type-converter/
这篇关于WP7:有条件地显示&隐藏数据模板中的控制元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!