Data Binding WPF Property to Variable

喜你入骨 提交于 2019-12-02 20:52:49

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/5533803/data-binding-wpf-property-to-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!