I have a custom media player object that I create in code behind from a user control. There can be 1 to 4 of these at any time, but i want to bind the volume and the mute property of only one to a xaml control EG.
The control is:
MediaControlplayer vcMediaPlayerMaster = new MediaControlplayer();
In this case the mute option to the ischecked
state of the control does not work. How can I hook the binding up to the properties of the control when it is instantiated in code behind ?
xaml is like this. The variable vcMediaPlayerMaster is a global variable in code behind. When i instantiated it i assumed its declaration as a global predefined variable would allow the xaml below to bind to it, but it seems not to be the case.
<ToggleButton x:Name="btnAudioToggle" ToolTip="Audio Mute/Unmute"
Click="BtnAudioToggle_OnClick" IsChecked="{Binding Mode =TwoWay,
ElementName=vcMediaPlayerMaster, Path=Mute}" BorderBrush="LightBlue"
Width="32" Height="32" Margin="0,5,10,10" Background="{StaticResource
IbAudio}" Style="{DynamicResource ToggleButtonStyle1}" > </ToggleButton>
I thought perhaps creating a binding in code behind may be the way to go, but i cant seem to find a simple example that explains the code behind process to do that to fit my case.
You could create a helper class to hold the currently active MediaPlayer.
As a simple example:
public class MediaPlayerHelper : INotifyPropertyChanged
{
private MediaControlplayer currentPlayer;
public static MediaPlayerHelper Instance { get; } = new MediaPlayerHelper();
public MediaControlplayer CurrentPlayer
{
get => this.currentPlayer;
set { /* Implement a setter with INotifyPropertyChanged */ }
}
// Implement INotifyPropertyChanged here
}
The binding to this would look like the following
<Slider Value="{Binding Volume, Source={x:Static helper:MediaPlayerHelper.Instance}}"/>
Don't forget to include the namespace in the opening tag of your class in XAML:
xmlns:helper="clr-namespace:SomeNamespace.Helper"
Now you just have to change the currently used MediaPlayer whenever it changes:
MediaPlayerHelper.Instance.CurrentPlayer = newCurrentPlayer;
Ok i finally got it to work. Applied the binding in code behind fully. I was able to bind the property i wanted to the ischecked property of a button to toggle the bool property of the mediaplayer object
MediaControlplayer vcMediaPlayerMaster = new MediaControlplayer();
Binding myMuteBinding = new Binding("Mute");
myMuteBinding.Source = vcMediaPlayerMaster;
myMuteBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
myMuteBinding.Mode = BindingMode.TwoWay;
btnAudioToggle.SetBinding(SimpleButton.IsCheckedProperty, myMuteBinding);
So this worked fine for me and i used the same principle to bind other properties.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.