听说我在将数据绑定(bind)到 Windows Phone 中的文本 block 时感到困惑
我有文本 block
<TextBlock Name="strytxt"
Text="{Binding STORY}"
Height="auto"
Width="Auto"
TextWrapping="Wrap"/>
有时在 STORY 对象中我有空值/空值 那时我在我的 UI 中获得了一些空间
现在,如果我在该行中得到 Null,我想让文本框的可见性变为折叠状态 我该怎么做
最佳答案
要在 Binding 值为 null 时更改 TextBlock 的可见性,您需要使用从 null/not null 转换为 Visible/Collapsed 的 Converter。
这是一个转换值的转换器。转换器将空字符串作为 null 处理,因此它为 string.empty
返回 Collapsed
。:
public class NullToVisibilityConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
bool isVisible = value == null ? false : true;
if (isVisible) {
string stringValue = value as string;
if (stringValue != null) {
isVisible = string.IsNullOrEmpty(stringValue) ? false : true;
}
}
if (System.ComponentModel.DesignerProperties.IsInDesignTool) {
return Visibility.Visible;
}
return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
您可以按如下方式将转换器应用于 TextBlock:
<UserControl.Resources>
<local:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
</userControl.Resources>
<TextBlock Name="strytxt"
Visibility="{Binding STORY, Converter={StaticResource nullToVisibilityConverter}}"/>
另一种选择是当值为空时显示文本,您可以在绑定(bind)中指定
<TextBlock Name="strytxt"
Text="{Binding STORY, TargetNullValue='is Null'}"/>
关于c# - 我们如何在将数据绑定(bind)到 Windows Phone 中的文本 block 时处理空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17669788/