WP7:有条件地展示&隐藏数据模板中的控件元素

时间:2012-05-05 16:27:54

标签: c# windows-phone-7 xaml silverlight-3.0

我有一个带有ListBox控件的笔记应用程序,它列出了ObservableCollection<Note> Notes中的所有可用笔记。 class Note具有

等属性
String Title;
bool Has_Reminder;
DateTime Reminder_Date;

我想要的是,如果Reminder_Date为真,则仅显示显示Has_Reminder的TextBlock元素。但我不知道如何从我的自定义控件NoteListItem访问此属性。其this.DataContext属性为null,但控件仍然正确显示ListBox ItemsSource传递的Note的绑定属性。我怎样才能做到这一点?

感谢您的帮助。

我尝试读取构造函数中的属性,但这些属性不起作用:

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>

1 个答案:

答案 0 :(得分:3)

您知道如何使用转换器吗?您的转换器会将bool转换为可见性,然后您可以将TextBlock的可见性绑定到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/

相关问题