How can I bind a xaml property to a static variabl

2020-02-20 22:38发布

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}" />

标签: c# wpf xaml
3条回答
我只想做你的唯一
2楼-- · 2020-02-20 23:13

You can use the newer x:Bind to do this simply using:

<TextBlock Text="{x:Bind YourClassName.PropertyName}"/>
查看更多
别忘想泡老子
3楼-- · 2020-02-20 23:24

You can't actually bind to a static property (INotifyPropertyChanged makes sense on instances only), so this should be enough...

{x:Static my:MyTestStaticClass.MyProperty}  

or e.g.

<TextBox Text="{x:Static my:MyTestStaticClass.MyProperty}" Width="500" Height="100" />  

make sure you include the namespace - i.e. define the my in the XAML like xmlns: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 (or OneWayToSource) binding:

Binding binding = new Binding();
//binding.Source = typeof(MyStaticClass);
// System.InvalidOperationException: 'Binding.StaticSource cannot be set while using Binding.Source.'
binding.Path = new PropertyPath(typeof(MyStaticClass).GetProperty(nameof(MyStaticClass.Left)));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.SetBinding(Window.LeftProperty, 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, implement INotifyPropertyChanged 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).

查看更多
▲ chillily
4楼-- · 2020-02-20 23:28

First of all you can't bind to variable. You can bind only to properties from XAML. For binding to static property you can do in this way (say you want to bind Text property of TextBlock) -

<TextBlock Text="{Binding Source={x:Static local:YourClassName.PropertyName}}"/>

where local is namespace where your class resides which you need to declare above in xaml file like this -

xmlns:local="clr-namespace:YourNameSpace"
查看更多
登录 后发表回答