I have this xaml file in which I try to bind a Text-block Background to a static variable in another class, how can I achieve this ?
I know this might be silly but I just moved from Win-forms and feeling a little bit lost.
here is what I mean:
<TextBlock Text="some text"
TextWrapping="WrapWithOverflow"
Background="{Binding Path=SomeVariable}" />
You can use the newer
x:Bind
to do this simply using:You can't actually bind to a static property (INotifyPropertyChanged makes sense on instances only), so this should be enough...
or e.g.
make sure you include the
namespace
- i.e. define themy
in the XAML likexmlns:my="clr-namespace:MyNamespace"
EDIT: binding from code
(There're some mixed answers on this part so I thought it made sense to expand, have it in one place)
OneTime
binding:You could just use
textBlock.Text = MyStaticClass.Left
(just careful where you place that, post-init)TwoWay
(orOneWayToSource
) binding:...of course if you're setting Binding from the code remove any bindings in XAML.
OneWay
(property changes from the source):And if you'd need to update the target (i.e. the control's property, Window.Left in this case) on the source property changes, that can't be achieved with the static class (as per my comment above, you'd need the
INotifyPropertyChanged
implemented, so you could just use a wrapper class, implementINotifyPropertyChanged
and wire that to a static property of your interest (providing you know how to track you static property's changes, i.e. this is more of a 'design' issue from this point on, I'd suggest redesigning and putting it all within one 'non-static' class).First of all you can't bind to
variable
. You can bind only toproperties
from XAML. For binding to static property you can do in this way (say you want to bindText
property ofTextBlock
) -where
local
is namespace where your class resides which you need to declare above in xaml file like this -