数据绑定WPF属性到变量 [英] Data Binding WPF Property to Variable
问题描述
首先,确保您的代码实现INotifyPropertyChanged。
示例: http://www.codekeep.net/snippets /4c7ed2e5-7e3b-40b4-b976-d54b54d9bf5b.aspx
所有这一切都是通知UI该值的值已更改的方法,需要抓住绑定的新价值。
第二件事是您需要以某种方式从代码中的其他模块访问变量,然后参考在你的代码背后使用一个Property。如果您不熟悉的属性示例:
http://www.xtremevbtalk.com/showthread.php?p=688701
现在的诀窍是,当你设置该属性,您还可以调用notify属性更改事件。
公共属性卷()
获取
Volume()= YourModuleVolume
End Get
Set(ByVal Value)
YourModuleVolume = Value
'Call NotifyPropertyChanged(Volume)here
结束集
结束属性
我不记得如果代码背后的代码自动将自己设置为用户控件的DataContext,因此您可能希望在构造函数中放置this.DataContext = this或VB.NET等效项。通常DataContext从您的ViewModel自动拉出。基本上说,使用指定的类(也就是后面的代码)作为所有数据绑定的源。
然后在XAML中这是一个通常的数据绑定。 b
$ b
< YourControl Volume ={Binding Volume}/>
作为附注,这真的不是一般通常关于设置WPF应用程序的方式,所以这种情况有点奇怪。如果您打算对WPF做很多工作,您可能需要查看Josh Smith在MVVM上的资源 - 这实际上是WPF应用程序的预期架构。
最好的运气!
I have a project in WPF 4 and VB.net 2010. I want to bind the volume property of a mediaelement to a variable in another module. Mind you, the variable is in the correct data type, so no conversion is necessary. How do I do this?
First, make sure that your code behind implements INotifyPropertyChanged.
Example here: http://www.codekeep.net/snippets/4c7ed2e5-7e3b-40b4-b976-d54b54d9bf5b.aspx
All that is is a way to notify the UI that value for the Volume has changed and it needs to grab the new value on the binding.
The second thing is you'll need to somehow access the variable from the other module in your code behind, and then reference that in your code behind using a Property. Examples of properties here, if you're not familiar:
http://www.xtremevbtalk.com/showthread.php?p=688701
Now the trick is, when you set the property, you'll want to also call the notify property changed event.
Public Property Volume()
Get
Volume() = YourModuleVolume
End Get
Set(ByVal Value)
YourModuleVolume = Value
'Call NotifyPropertyChanged("Volume") here
End Set
End Property
I can't remember if the code behind class automatically sets itself as the DataContext for the User Control, so you may want to drop in a "this.DataContext = this" or VB.NET equivalent in your constructor. Usually the DataContext is pulled in automagically from your ViewModel. Basically, that says to use the specified class (aka code behind) as the source for all data bindings.
Then in XAML it's a usual databinding.
<YourControl Volume="{Binding Volume}" />
As a side note, this is really not how one usually goes about setting up a WPF application, so this scenario's a little odd. If you plan to do much with WPF, you may want to look into Josh Smith's resources on MVVM - that's really the intended architecture of a WPF application.
Best of luck!
这篇关于数据绑定WPF属性到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!