Can I bind a textblock's content to only part of a string in an observable collection?
I'm relatively new to WPF so apologies if there is an obvious or simple answer to this that I am not seeing.
I have an ObservableCollection of items with several different sized images for each. The relative path for each image is in string format, with image files stored in different subfolders.
The image paths are in the format:
imagepath = @"subfolder/subfolder/filename.png"
I would like to be able to bind to a textblock but show only the filename below each image without changing the image path. Is this possible? I gather it would require a converter of some sort, but I have been struggling with it as I cannot find a reasonable way of showing only part of a string.
Thanks for your help.
Edit
To clarify, my 'value' is non-static, referencing items in an observable collection eg.
ObservableCollection<Icon> items = new ObservableCollection<Item>();
items.Add(new Item{imagename = "someimagename",
imagepath= "somefolder/somesubfolder/somefilename.png"}) etc...
I'm only starting to get to grips with 'getting' values from my collection. Any help with filling in the 'value.Tostring()' part to get dynamic values for item.imagepath would be really appreciated so I can get this working.
I've currently been trying along these lines:
class getFilenameFromPathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
开发者_Python百科 System.Globalization.CultureInfo culture)
{ Item item = value as Item;
PropertyInfo info = value.GetType().GetProperty("imagepath");
string filename = info.GetValue(item, null).ToString();
return System.IO.Path.GetFileNameWithoutExtension(filename); }
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
But I'm getting an Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
Thanks
XAML as specified by fatty.
Your converter should look like:
class getFilenameFromPathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Path.GetFileName(value.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
You will need to enlist the help of a converter to get this value.
Create a class that implements IValueConverter, and in the Convert method return the part of the string that you want to display.
In your TextBlock, you bind to the property like {Binding Path=imagepath, Converter={StaticResource getFilenameFromPathConverter}}
精彩评论