Search code examples
c#.netwpfxaml

Conditional in XAML file?


I have the following XAML file:

<MediaElement Name="mediaElementOne"
              LoadedBehavior="Manual"
              Stretch="UniformToFill"
              ScrubbingEnabled="True"
              MediaOpened="Media_Success"
              MediaFailed="Media_Failure"/>

The MediaOpened property currently calls the "Media_Success" when the media loaded successfully.

My issue is with MediaFailed, because I only want MediaFailed to fire on a boolean, meaning I need this to be conditional based on a boolean in my .cs file for the aforementioned XAML file.

How do I write a conditional in a XAML file? Or how would I be able to do this on the .cs file.

Right now as soon as .net believes the media failed it fires the Media_Failure function. I don't want it to fire the Media_Failure function when a specific boolean is set to false and for reasons far outside the scope of this question I can't handle the condition inside of the Media_Failure function.

Additional info: Here is the method it fires on the .cs file:

private void Media_Failure(object sender, ExceptionRoutedEventArgs e){...}

Solution

  • A pattern like this comes to mind where you set or clear the MediaFailed event handler based on the boolean, which you make a property with a getter/setter.

    private bool _isMediaFailureEnabled;
    public bool isMediaFailureEnabled
    {
        get
        {
            return _isMediaFailureEnabled;
        }
    
        set
        {
            if (_isMediaFailureEnabled != value)
            {
                _isMediaFailureEnabled = value;
                if (_isMediaFailureEnabled)
                {
                    mediaElementOne.MediaFailed += MediaElementOne_MediaFailed;
                }
                else
                {
                    mediaElementOne.MediaFailed -= MediaElementOne_MediaFailed;
                    // OR
                    // mediaElementOne.MediaFailed = null;
                }
            }
        }
    }
    

    You will have to inspire from this pattern and adapt to your code, but this should accomplish what you want.

    Edit:

    Thought about this more for some reason and arrived at an alternative which is very similar to what Maurice came up with, by using a level of abstraction to solve the problem.

    Define a wrapper or the failed event:

    MediaFailed="Media_Failure_Wrapper"
    

    Always let this be called, and only call your original event handler when your boolean is true:

    private void Media_Failure_Wrapper(object sender, ExceptionRoutedEventArgs e)
    {
        if (_isMediaFailureEnabled)
        {
            return Media_Failure(sender, e);
        }
        else
        {
            e.Handled = true;
            return;
        }
    }