WP7: Conditionally show & hide control elements in Data Templates

旧巷老猫 提交于 2019-12-13 03:38:53

问题


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>

回答1:


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/



来源:https://stackoverflow.com/questions/10463759/wp7-conditionally-show-hide-control-elements-in-data-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!