如果Silverlight中的第一个属性为null,则绑定到第二个属性

时间:2011-09-12 19:02:34

标签: c# silverlight xaml data-binding

我有一个类,其中对象的名称可以为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;

但我无法更改我的模型对象。有没有好办法呢?

我考虑过使用转换器,但在我看来,我必须将转换器绑定到对象本身,而不是Name属性。这没关系,但是当名称或标识符发生变化时,我将如何重新绑定?如果我手动收听对象的IValueConverter事件,INotifyPropertyChanged似乎无法强行重新转换。

有关最佳方法的任何想法吗?

4 个答案:

答案 0 :(得分:3)

您可以更改Binding,以便它直接绑定到您的Thing实例:

<DataTemplate x:Key="ThingTemplate">
    <Grid>
        <TextBlock TextWrapping="Wrap" Text="{Binding .,Converter={StaticResource ConvertMyThingy}" />
    </Grid>
</DataTemplate>

然后使用从传递的Instance实例返回NameThing的转换器

public class ConvertMyThingyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var thing= value as Thing;
        if(thing == null)
           return String.Empty;
        return thing.Name ?? thing.Identifier;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

答案 1 :(得分:2)

在WPF中,您可以通过实施IMultiValueConverter轻松完成此操作。遗憾的是,尽管有workarounds written for Silverlight.

,但Silverlight并不直接支持此功能

答案 2 :(得分:0)

Converter未绑定到NameObject,它绑定到Text属性绑定。 因此,每次为Text赋值时都会调用它。在Converter内进行选择,以选择Text属性的样子。

可能的解决方案之一是使NameAndIdentifier字符串特殊属性可以根据模型的NameIdentifier属性从Converter中分配。

答案 3 :(得分:0)

您需要在ViewModel / Presenter中创建自定义显示属性(或者您想要调用它的任何内容)。基本上,您上面发布的代码必须进行修改,并添加到其中:

public readonly string DisplayName
{
    get
    {
        return Name ?? Identifier;
    }
}

据我所知,任何其他方式都会成为黑客。