[英]WP7: Conditionally show & hide control elements in Data Templates
I have a note application with a ListBox control, which lists all the available notes from the ObservableCollection<Note> Notes
. 我有一个带有ListBox控件的便笺应用程序,该控件列出了ObservableCollection<Note> Notes
所有可用ObservableCollection<Note> Notes
。 class Note
has attributes like class Note
具有类似的属性
String Title;
bool Has_Reminder;
DateTime Reminder_Date;
What I want is that the TextBlock element, which shows the Reminder_Date
, is only shown, if Has_Reminder
is true. 我想要的是,如果Has_Reminder
为true,则仅显示TextBlock元素,该元素显示Reminder_Date
。 But I do not know how to access this attribute from my custom control NoteListItem. 但是我不知道如何从我的自定义控件NoteListItem访问此属性。 Its this.DataContext
attribute is null
, but the control still properly displays the Note's bound attributes handed down by the ListBox ItemsSource. 它的this.DataContext
属性为null
,但控件仍正确显示ListBox ItemsSource传递的Note的绑定属性。 How can I achieve that? 我该如何实现?
Thanks for your help. 谢谢你的帮助。
I tried to read the attributes in the constructor, which did not work: 我试图读取构造函数中的属性,但无法正常工作:
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 control NoteListItem控件
<Grid x:Name="LayoutRoot" >
<TextBlock x:Name="Title" Text="{Binding Title}" />
<TextBlock x:Name="Reminder_Date" Text="{Binding Reminder_Date}" />
</Grid>
NoteList control: NoteList控件:
<ListBox x:Name="NoteListBox" ItemsSource="{Binding Notes}" >
<ListBox.ItemTemplate>
<DataTemplate>
<local:NoteListItem />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
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
: 您的转换器会将bool转换为Visibility,然后可以将TextBlock的Visibility绑定到Has_Reminder
:
<TextBlock x:Name="Reminder_Date" Text="{Binding Reminder_Date}" Visibility="{Binding Has_Reminder, Converter={...}}"/>
This might help: http://www.jeff.wilcox.name/2008/07/visibility-type-converter/ 这可能会有所帮助: http : //www.jeff.wilcox.name/2008/07/visibility-type-converter/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.