Hello, I'm starting to work with WPF and I've created a Custom Markup Extension starting section of this tutorial . The intent of this Markup Extension is to simulate the declarative conditions that are found in WebFrameworks such as the Angular2 or the VueJS for the web, for example:
<!-- se não atende a condição, não insere o elemento -->
<div *ngIf="condition">...</div> <!-- angular -->
<div v-if="condition">...</div> <!-- vue -->
<!-- retorna para a variável -->
<input type="text" [disabled]="condition" /> <!-- angular -->
<input type="text" :disabled="condition" /> <!-- vue -->
<!-- atribui uma classe ao elemento -->
<div [ngClass]="{ 'foo': condition }"></div> <!-- angular -->
<div :class="{ 'foo': condition }"></div> <!-- vue -->
As XAML
is very similar to HTML
and I already have the habit of working with these frameworks, what I try to simplify is the maximum of the form of comparison, bypassing the variation of a variable from this condition. So I could, for example change the text of a button, visibility, color, etc ...
Below is my Markup:
namespace WPF
{
public class If : MarkupExtension
{
public bool Condition { get; set; }
public object True { get; set; }
public object False { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (Condition & (True != null && False != null))
return Condition ? True : False;
else
throw new InvalidOperationException("Inputs cannot be blank");
}
}
}
The intent of this Markup Extension is to literally mimic the If operator for tenant operations, having its use like this:
<Window x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF">
<Grid>
<!-- ocultar ou mostrar -->
<TextBlock Visibility="{fn:If Condition=/* ?? */, True='Visible', False='Colapsed'}"/>
<!-- mudança de variável -->
<TextBlock Text="{fn:If Condition=/* ?? */, True='Is true!', False='Is not true!'}"/>
<!-- Mudança de estilo (como as classes html) -->
<TextBlock Text="{fn:If Condition=/* ?? */, True={DynamicResource Foo}, False={DynamicResource Bar}"/>
</Grid>
</Window>
My problem is that I'm not sure how I can declare a condition directly in XAML using the Binding
of a variable. Let's say that in my class MainWindow.cs
I have a variable like this:
namespace WPF
{
public partial class MainWindow
{
private int randomNumber { get; set; }
public MainWindow()
{
Random rnd = new Random();
randomNumber = rnd.Next(0, 10);
}
}
}
How do I do a ternary comparison directly in XAML? For example, how do I check if the number is greater than 6, that is (randomNumber > 6 ? 'Is true!' : 'Is not true!')
Edit
I even found this solution but I do not agree to be bound to create this all to meet a simple ternary operation, after all if I have to create a class and a convert to every possibiliade / attribute, I would understand it as a language flaw ...