许多 ASP.NET 数据绑定控件公开了一个 EmptyDataTemplate,当控件绑定到空数据源时呈现该模板。在我的 WP7 应用程序中,我也想在绑定到 ListBox 的数据源为空时显示一条友好消息。有没有一种相当优雅的方式来实现这一目标?最好与 caliburn.micro 集成/能够?
谢谢!!
许多 ASP.NET 数据绑定控件公开了一个 EmptyDataTemplate,当控件绑定到空数据源时呈现该模板。在我的 WP7 应用程序中,我也想在绑定到 ListBox 的数据源为空时显示一条友好消息。有没有一种相当优雅的方式来实现这一目标?最好与 caliburn.micro 集成/能够?
谢谢!!
我不喜欢为这样的功能使用代码。我宁愿建议在绑定标记中实现一个可用的 DataTemplateConverter 来实现这个确切的功能。
举个例子:
<ContentControl ContentTemplate="{Binding Converter={StaticResource templateConverter}, Path=yourbindingpath}"/>
转换器将在 xaml 文件的资源部分中实例化。
<myControls:EmptyDataTemplateConverter x:Key="templateConverter">
<myControls:EmptyDataTemplateConverter.NonEmpty>
<DataTemplate>[...]</DataTemplate>
</myControls:EmptyDataTemplateConverter.NonEmpty>
<myControls:EmptyDataTemplateConverter.Empty>
<DataTemplate>[...]</DataTemplate>
</myControls:EmptyDataTemplateConverter.Empty>
</myControls:EmptyDataTemplateConveter>
在这种情况下,Empty/NonEmpty 实现取决于您。
要了解如何实现这样的 ValueConverter,请参阅MSDN(或 google)
添加了样品。您可以使用 DataTemplate 的依赖项属性,但为了简单起见,我在这里 ometted。
public class EmptyDataTemplateConverter: IValueConverter
{
public DataTemplate Empty{get;set;}
public DataTemplate NonEmpty{get;set;}
// This converts the DateTime object to the DataTemplate to use.
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if(IsEmpty(value))
{
return this.Empty;
}
else
{
return this.NonEmpty;
}
}
//Your "empty/not empty" implementation here. Mine is rather... incomplete.
private bool IsEmpty(object value)
{
return value!=null;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
编辑:实现相同目标的其他方式,但更多的是“Silverlight 方式”。使用GoToStateAction和适当的触发器。将您的模板图形封装在 UserControl 中,并为此 UserControl 指定状态。这样,用户控件将根据触发器的行为(空/非空)而改变。
结果将与我之前的提议相同,但具有状态更改动画的额外好处,使用 DataTemplateConverter 很难实现(修改后的 TransitioningContentControl)。
不确定 caliburn.micro,但是例如,如果您要绑定到一个ObservableCollection<T>
(在我看来,这是绑定到任何东西的最佳集合),那么就有CollectionChanged
事件处理程序。
可以这么说:
ObservableCollection<string> c = new ObservableCollection<string>();
c.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(c_CollectionChanged);
在这里,在事件处理程序本身中,您可以检查触发集合是否为空:
void c_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (((ObservableCollection<string>)sender).Count == 0)
{
// Action here
}
}
Silverlight中没有开箱即用的此类功能。
但是,您可以做的是使用适当的消息创建一个,并使用转换器TextBlock
将它的可见性与ListBox
的ItemsSource绑定。该转换器应Visibility.Visible
在Count > 0和Count == 0Visibility.Collapsed
时返回。