简体   繁体   中英

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 . class Note has attributes like

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. 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?

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

<Grid x:Name="LayoutRoot" >
    <TextBlock x:Name="Title" Text="{Binding Title}" />
    <TextBlock x:Name="Reminder_Date" Text="{Binding Reminder_Date}" />
</Grid>

NoteList control:

<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 :

<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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM