سؤال

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/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top