我有一个对象的名称可以为null的类。
public class Thing
{
/// <summary>
/// The identifier of the thing
/// </summary>
/// <remarks>
/// This will never be null.
/// </remarks>
public string Identifier { get; set; }
/// <summary>
/// The name of the thing
/// </summary>
/// <remarks>
/// This MAY be null. When it isn't, it is more descriptive than Identifier.
/// </remarks>
public string Name { get; set; }
}
在Silverlight ListBox中,我使用DataTemplate,其中的名称绑定到TextBlock:
<DataTemplate x:Key="ThingTemplate">
<Grid>
<TextBlock TextWrapping="Wrap" Text="{Binding Name}" />
</Grid>
</DataTemplate>
但是,如果Name为null,则这显然不太好。理想情况下,我想使用与
string textBlockContent = thing.Name != null ? thing.Name : thing.Identifier;
但我无法更改模型对象。有什么好办法吗?
我曾考虑过使用Converter,但在我看来,我必须将Converter绑定到对象本身,而不是Name属性。很好,但是当“名称”或“标识符”更改时,我该如何重新绑定?如果我手动侦听对象的
IValueConverter
事件,则INotifyPropertyChanged
似乎没有任何方法可以强制进行重新转换。关于最佳方法的任何想法吗?
最佳答案
在WPF中,可以通过实现IMultiValueConverter轻松地做到这一点。不幸的是,尽管有workarounds written for Silverlight.,Silverlight不直接支持此功能。