开发者

Expressions in Databinding... possible? How to?

I have a collection databound to a ListBox. What I would like to do is show some UI based on whether or not some property of the member of the collection exists.

E.g.:

public class Widget
{
  public string foo;
  public string bar;
}

public ObservableCollection<Widget> Stuff;

XAML:

<ListBox ItemsSource="{Binding Stuff}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding foo}" 
                 Visiblity="{Binding 
                   (foo != null ? Visibility.Visible : Visibility.Colla开发者_JS百科psed)
                 }"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Note the Visibility attribute on the TextBlock. Clearly this isn't supported, but it should give you an idea of what I want to do.

One possible solution is that I could add a property to widget that looks like this:

public Visibility has_foo;

And then:

... Visibility="{Binding has_foo}" ...

But it seems awkward to have to generate these additional properties.

I suspect there is a much better way. Is there? How would you do it?

Thanks.


Create a value converter. Something like

public class NullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value != null ? Visibility.Visible : Visibility.Collapsed;
    }

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

Then add it something like

<YourUserControl.Resources>
   <NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
</YourUserControl.Resources>

<ListBox ItemsSource="{Binding Stuff}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding foo}" 
                 Visiblity="{Binding foo, 
                     Converter={StaticResource NullToVisibilityConverter}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Obviously I've not implemented ConvertBack (not really sure if you will be able to convert back) but you shouldn't need it in this instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜