简体   繁体   English

XAML 文件中的条件?

[英]Conditional in XAML file?

I have the following XAML file:我有以下 XAML 文件:

<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. MediaOpened属性当前在媒体加载成功时调用“Media_Success”。

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.我的问题是MediaFailed ,因为我只希望 MediaFailed 在布尔值上触发,这意味着我需要基于上述 XAML 文件的 .cs 文件中的布尔值来设置它。

How do I write a conditional in a XAML file?如何在 XAML 文件中编写条件? Or how would I be able to do this on the .cs file.或者我怎么能在 .cs 文件上做到这一点。

Right now as soon as .net believes the media failed it fires the Media_Failure function.现在,只要 .net 认为媒体失败,它就会触发 Media_Failure 函数。 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.我不希望它在特定布尔值设置为 false 时触发 Media_Failure 函数,并且由于远远超出此问题范围的原因,我无法处理 Media_Failure 函数内部的条件。

Additional info: Here is the method it fires on the .cs file:附加信息:这是它在 .cs 文件上触发的方法:

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

You can use triggers.您可以使用触发器。

This code is in reference to winrt xaml.此代码参考了 winrt xaml。 The same can you do in WPF:你可以在 WPF 中做同样的事情:

<Interactivity:Interaction.Behaviors>
    <Core:DataTriggerBehavior Binding="{Binding IsFailed}" Value="True">
      <Core:CallMethodAction MethodName="MediaFailed"/>
    </Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>

This will go with your media element.这将与您的媒体元素一起使用。

So, if your bool is true it will call a method.因此,如果您的 bool 为真,它将调用一个方法。

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.在您基于布尔值设置或清除 MediaFailed 事件处理程序的地方会想到这样的模式,您可以使用 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.出于某种原因,对此进行了更多思考,并通过使用抽象级别来解决问题,得出了与 Maurice 提出的非常相似的替代方案。

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;
    }
}

Here is a way to do it( without any extra lib like interactivity etc).这是一种方法(没有任何额外的库,如交互性等)。

Create a helper class: (which gives you flexibility to write down logic for events and/or behaviors and/or triggers and/or command bindings and/or a middle layer for event handling).创建一个辅助类:(它使您可以灵活地为事件和/或行为和/或触发器和/或命令绑定和/或用于事件处理的中间层编写逻辑)。

public class RoutedEventTrigger : FrameworkElement
{       
    RoutedEvent _routedEvent;
    public RoutedEvent RoutedEvent
    {
        get { return _routedEvent; }
        set { _routedEvent = value; }
    }

    private Action<object, RoutedEventArgs> handler;
    public Action<object, RoutedEventArgs> Handler
    {
        get { return handler; }
        set { handler = value; }
    }

    public static DataTemplate GetTemplate(DependencyObject obj)
    {
        return (DataTemplate)obj.GetValue(TemplateProperty);
    }

    public static void SetTemplate(DependencyObject obj, DataTemplate value)
    {
        obj.SetValue(TemplateProperty, value);
    }

    public static readonly DependencyProperty TemplateProperty =
        DependencyProperty.RegisterAttached("Template",
        typeof(DataTemplate),
        typeof(RoutedEventTrigger),
        new PropertyMetadata(default(DataTemplate), OnTemplateChanged));

    private static void OnTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        DataTemplate dt = (DataTemplate)e.NewValue;
        if (dt != null)
        {
            dt.Seal();
            RoutedEventTrigger ih = (RoutedEventTrigger)dt.LoadContent();
            (d as FrameworkElement).AddHandler(ih.RoutedEvent, new RoutedEventHandler(ih.OnRoutedEvent));                
        }
    }

    void OnRoutedEvent(object sender, RoutedEventArgs args)
    {
        Handler.Invoke(sender, args);
    }
    
} 

XAMl: (Just set the helper class properties from XAML and this will work with any element.) XAMl:(只需从 XAML 设置帮助程序类属性,这将适用于任何元素。)

<Button Height="100" Width="200" Content="Click" Name="mybutton" >
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsEventAttached}" Value="true">
                    <Setter  Property="local:RoutedEventTrigger.Template">
                        <Setter.Value>
                            <DataTemplate>
                                <local:RoutedEventTrigger RoutedEvent="Button.Click" Handler="MySlider_ValueChanged" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM