dotnet / dotnet/wpf

CollectionView.NewItemPlaceholder should have a setter!

Open
#8,258 14 comments 0 reactions 0 assignees View on GitHub
Enhancement Requested
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

For advanced `ListBox` usage, we need to check in code if items are of type [NamedObject](https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/WindowsBase/MS/Internal/NamedObject.cs). Similarly, we needed a `DataTemplate` for this specific type. Obviously, this is **not** possible since the `NamedObject` type is **internal**. Maybe for good reasons.

### A hacky solution
So we decided to assign the `CollectionView.NewItemPlaceholder` value to an instance of a custom (known) type. See [CollectionView.cs(757)](https://github.com/dotnet/wpf/blob/b9b48871d457fc1f78fa9526c0570dae8e34b488/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Data/CollectionView.cs#L757C30-L757C48). It sure works, but we have to use an ugly **reflection hack** to set our custom placeholder value:

```c#
internal class MyListCollectionView : ListCollectionView, IMyListCollectionView
{
static MyListCollectionView()
{
#if FUTURE_DOT_NET_VERSION
NewItemPlaceholder = new MyNewItemPlaceholder("NewItemPlaceholder");
#else
ApplyItemPlaceHolderHack(); // :'(
#endif
}

private static void ApplyItemPlaceHolderHack()
{
var fi = typeof(CollectionView).GetField("_newItemPlaceholder", BindingFlags.Static | BindingFlags.NonPublic) ?? throw new NotSupportedException();
fi.SetValue(null, new MyNewItemPlaceholder("NewItemPlaceholder"));
}

// ...
}
```

### Add a setter!
In `CollectionView.cs`, can you please add a setter as shown below? That would make it easier to style the "new item" part of a `ListBox`.
```c#
public static object NewItemPlaceholder
{
get { return _newItemPlaceholder; }
set { _newItemPlaceholder = value; } // <--- This is the key!
}
```

Should be a no-brainer (even with the tiny API change above). Can you add this in `.NET 8`?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.