dotnet / dotnet/wpf

Provide more built-in markup extensions

Open
#455 3 comments 6 reactions 0 assignees View on GitHub
API suggestion
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

Sometimes I found that if we use some custom markup extensions, which can make our code easier.

For example, if we want to control the visibility of a ui element and there is a bool property (named `IsA`) in our view model, we usually use the `BooleanToVisibilityConverter` to convert the bool type to the visibility enum type in xaml, but there is another element that has the opposite behavior and it wants to be hidden when the boolean property (named `IsA`) is `true`. Now, we will have two options: 1) add a new bool property named `IsNotA`; 2) add a new converter named `NotBooleanToVisibilityConverter`. But I think we have a third choice: use a custom markup extension named `ComposeExtension` for it, like below:
```xml
?:`) in xaml. I know we can use the `Trigger` to implement it, like below:
```xml



<Setter Property="Content" Value="{StaticResource LoadingImage}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsLoaded}" Value="True">
<Setter Property="Content" Value="{StaticResource LoadedImage}" />
</DataTrigger>
</Style.Triggers>



```
But I think the above code is too long. If we have the `IfExtension`, we can write it in the following form: (see [here](https://github.com/DingpingZhang/WpfExtensions/blob/master/WpfExtensions.Xaml/Markup/IfExtension.cs) for its implementation)
```xml

```

But the implementation of `IfExtension` has a known issue: I chose to implement `IfExtension` with `MultiBinding`, in order to get the correct `DataContext` when the values of `IfExtension.True` and `IfExtension.False` are binding, but `MultiBinding.Bindings` CANNOT accept values of `MultiBinding` type, so I cannot set a derived class of `MultiBinding` for `IfExtension.True` and `IfExtension.False` , or use `IfExtension` in a nested form.

I don't quite understand how to create a custom markup extension that gets the correct `DataContext` when the markup needs to accept some `BindingBase` type values. I found that there are many methods to implement `Binding` or `MultiBinding` 's code is `internal` (e.g.: `CreateBindingExpression()`, see [here](https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Data/MultiBinding.cs)), and I'm not sure if I need to use these internal functions perfectly to implement `IfExtension`.

In addition, I also want to know what other interesting custom markup extensions you often use, I hope you can share them here, thank you! :)

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.