如何将xaml属性绑定到另一个类中的静态变量?

a7m*_*dx7 32 c# wpf xaml

我有这个xaml文件,我尝试将Text-block Background绑定到另一个类中的静态变量,我该如何实现?

我知道这可能很愚蠢,但我刚从Win-forms中感动并感到有点失落.

这就是我的意思:

<TextBlock Text="some text"
           TextWrapping="WrapWithOverflow"
           Background="{Binding Path=SomeVariable}" />
Run Code Online (Sandbox Code Playgroud)

Roh*_*ats 49

首先你无法绑定variable.您只能绑定到propertiesXAML.对于绑定到静态属性,您可以这样做(假设你想绑定Text属性TextBlock) -

<TextBlock Text="{Binding Source={x:Static local:YourClassName.PropertyName}}"/>
Run Code Online (Sandbox Code Playgroud)

这里local是你的类所在,你需要在这样的XAML文件上面声明命名空间-

xmlns:local="clr-namespace:YourNameSpace"
Run Code Online (Sandbox Code Playgroud)

  • 从转换器返回画笔 - "返回新的SolidColorBrush(值为颜色)" (2认同)

NSG*_*aga 11

你实际上不能绑定到静态属性(INotifyPropertyChanged只对实例有意义),所以这应该足够了......

{x:Static my:MyTestStaticClass.MyProperty}  
Run Code Online (Sandbox Code Playgroud)

或者例如

<TextBox Text="{x:Static my:MyTestStaticClass.MyProperty}" Width="500" Height="100" />  
Run Code Online (Sandbox Code Playgroud)

确保包括namespace- 即my在XAML中定义xmlns:my="clr-namespace:MyNamespace"


编辑:从代码绑定
(这部分有一些混合的答案所以我认为扩展有意义,把它放在一个地方)


OneTime 捆绑:

你可以使用textBlock.Text = MyStaticClass.Left(只需要小心放置它,post-init)

TwoWay(或OneWayToSource)绑定:

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);
Run Code Online (Sandbox Code Playgroud)

...当然,如果您从代码中设置Binding,请删除XAML中的任何绑定.

OneWay (财产从源头变化):

如果你需要在源属性上更新目标(即控件的属性,本例中为Window.Left),那么静态类无法实现(根据我上面的评论,你需要已INotifyPropertyChanged实现,所以你可以使用一个包装类,实现INotifyPropertyChanged并将其连接到你感兴趣的静态属性(让你知道如何跟踪静态属性的变化,从这一点来看,这更像是一个'设计'问题,我建议重新设计并将其全部放在一个"非静态"类中.