Data Binding WPF Property to Variable

后端 未结 1 1333
悲哀的现实
悲哀的现实 2021-01-28 03:35

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 ty

相关标签:
1条回答
  • 2021-01-28 03:54

    First, make sure that your code behind implements INotifyPropertyChanged.

    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.

    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!

    0 讨论(0)
提交回复
热议问题