简体   繁体   English

从属性绑定属性

[英]Binding property from a property

how can I do a bind if the property to show is a property from a property, like this case: 如果要显示的属性是来自属性的属性,我该如何进行绑定,例如这种情况:

Xaml: XAML:

<TextBox Text="{Binding log.Message}"/>  ????

In the class defined as Datacontext, I declare a log variable: 在定义为Datacontext的类中,我声明了一个日志变量:

public Log log = new Log();

the Log class: 日志类:

public class Log : INotifyPropertyChanged
{
    public static string Message{ get { return message; } }
  ....

Your question is a bit unclear to me, but i give it a shot: 您的问题对我来说还不清楚,但我试一下:

If the DataContext is an instance of the Log class, and the property is non static. 如果DataContextLog类的实例,并且该属性是非静态的。 Than the proper binding would be 比适当的约束是

<TextBox Text="{Binding Message}"/> 

From there you can easily nest your bindings. 从那里您可以轻松地嵌套您的绑定。 For example if Log would have an instance of a class 例如,如果Log会有一个类的实例

public class Log {
     public MessageHandler Message {get;set;}
}

which would have a property LocalizedMessage , it would simply be 它将具有LocalizedMessage属性,它只是

<TextBox Text="{Binding Message.LocalizedMessage}"/> 

If you want to bind to a static property, which your Message property currently is: 如果要绑定到静态属性,则您的Message属性当前为:

<TextBox Text="{Binding Source={x:Static MyNs:Log.Message}, Path=.}"/> 

You can't bind static properties to XAML. 您不能将静态属性绑定到XAML。 Only .Net 4.5 enables that, and even that with some work. 只有.Net 4.5才能做到这一点,甚至还需要一些工作。 see: WPF 4.5 – Part 9 : binding to static properties . 请参见: WPF 4.5 –第9部分:绑定到静态属性 You can find the way there. 您可以找到那里的路。

If you can't use .Net 4.5, check out this SO thread for another workaround. 如果您不能使用.Net 4.5,请查看此SO线程以获取其他解决方法。

您编写的内容存在问题,即Message是一个静态属性,因此您不是想从log对象中获取它,而是从Log类中获取它:

<Window.Resources> <local:Log x:Key="logClass"/> </Window.Resources>

<TextBox Text="{Binding Source={StaticResource logClass}, Path=Message}"/

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

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