Reputation: 73
So I am currently trying to bind a public static SolidColorBrush to a "Filled" property on a Rectangle inside a ResourceDirectory Style (inisde App.xaml). But I always get the Exception
"Type 'x' used after '{' must be a Markup Extention. Error code 0x09c6."
My xaml code looks like this (inside App.xaml):
<Rectangle
x:Name="SelectionIndicator"
Width="4"
Height="24"
Fill="{x:Bind SomeNamespace:SomeClass.SomeColor}"/>
and my codebehind looks like this (inside public class called "SomeClass" in Namespace called "SomeNamespace"):
public static SolidColorBrush SomeColor = new(Colors.Red);
I know its possible to bind to a public static property with x:Bind in WinUI/UWP but this somehow doesnt work. I really need to bind from some code behind so I can implement INotifyPropertyChanged so I cant just create a new color resource. What is the correct way to implement my wanted behavior? Thanks in advance!
Upvotes: 1
Views: 394
Reputation: 98
You probably can't call your PropertyChanged event handler from a static property. You'll need an instance.
Consider storing the brush as a non-static property in a wrapper class. You can instantiate this class as a resource in your App.xaml file and use it across your application.
ColorStorer is a class to store the SolidColorBrush:
public class ColorStorer: INotifyPropertyChanged
{
private SolidColorBrush scb = new SolidColorBrush(Colors.Red);
public SolidColorBrush Scb
{
get
{
return scb;
}
set
{
if (value as SolidColorBrush != null)
{
scb = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Instantiate it in Application.Resources in App.xaml:
<Application.Resources>
<ResourceDictionary>
<local:ColorStorer x:Key="TestAppColorStorer" />
</ResourceDictionary>
</Application.Resources>
Use it in your views and controls:
<Rectangle
Width="100"
Height="50"
HorizontalAlignment="Center"
Fill="{Binding Scb, Source={StaticResource TestAppColorStorer}, Mode=OneWay}" />
Upvotes: 1