繁体   English   中英

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

[英]How can I bind a xaml property to a static variable in another class?

我有这个 xaml 文件,我尝试将文本块背景绑定到另一个类中的静态变量,我该如何实现?

我知道这可能很愚蠢,但我刚从 Win-forms 转移过来,感觉有点失落。

这就是我的意思:

<TextBlock Text="some text"
           TextWrapping="WrapWithOverflow"
           Background="{Binding Path=SomeVariable}" />

首先,你不能绑定到variable 您只能绑定到 XAML 中的properties 要绑定到静态属性,您可以通过这种方式进行(假设您要绑定TextBlock Text属性)-

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

其中local是您的类所在的命名空间,您需要在上面的 xaml 文件中像这样声明 -

xmlns:local="clr-namespace:YourNameSpace"

您实际上无法绑定到静态属性(INotifyPropertyChanged 仅对实例有意义),所以这应该足够了...

{x:Static my:MyTestStaticClass.MyProperty}  

或例如

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

确保包含namespace - 即在 XAML 中定义my ,如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);

...当然,如果您从代码中设置绑定,请删除 XAML 中的所有绑定。

OneWay (来自源头的属性更改):

如果您需要在源属性更改时更新目标(即控件的属性,在这种情况下为 Window.Left),则无法通过静态类实现(根据我上面的评论,您需要实现了INotifyPropertyChanged ,因此您可以只使用包装类,实现INotifyPropertyChanged并将其连接到您感兴趣的静态属性(前提是您知道如何跟踪静态属性的更改,即从这一点来看这更像是一个“设计”问题上,我建议重新设计并将其全部放在一个“非静态”类中)。

您可以使用较新的x:Bind来执行此操作,只需使用:

<TextBlock Text="{x:Bind YourClassName.PropertyName}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM