如何使用MVVM架构重用XAML for WinRT应用程序中的交互行为
要绑定“已加载”和“已卸载”事件,我在XAML页面中使用以下代码:如何使用MVVM架构重用XAML for WinRT应用程序中的交互行为,xaml,mvvm,windows-runtime,behavior,reusability,Xaml,Mvvm,Windows Runtime,Behavior,Reusability,要绑定“已加载”和“已卸载”事件,我在XAML页面中使用以下代码: <Page ...> <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="Loaded"> <core:InvokeCommandAction Command="{Binding LoadedCommand}" /> </core:EventTr
<Page ...>
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding LoadedCommand}" />
</core:EventTriggerBehavior>
<core:EventTriggerBehavior EventName="Unloaded">
<core:InvokeCommandAction Command="{Binding UnloadedCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
<Grid />
</Page>
一切正常,但我复制到每个视图相同的代码位?我怎样才能让它可重复使用
编辑
我使用本文中的代码创建了一个附加属性
我的附加属性如下所示:
public static class UiBehaviors
{
public static readonly DependencyProperty AttachedTriggersProperty = DependencyProperty.RegisterAttached("AttachedTriggers", typeof(EventTriggerCollection), typeof(UiBehaviors), new PropertyMetadata(null, OnAttachedTriggersChanged));
private static void OnAttachedTriggersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BehaviorCollection triggers = Interaction.GetBehaviors(d);
if (e.OldValue != null)
{
foreach (EventTriggerBehavior trigger in (EventTriggerCollection)e.OldValue)
triggers.Remove(trigger);
}
if (e.NewValue == null)
return;
foreach (EventTriggerBehavior trigger in (EventTriggerCollection)e.NewValue)
triggers.Add(trigger);
}
public static void SetAttachedTriggers(DependencyObject element, EventTriggerCollection value)
{
element.SetValue(AttachedTriggersProperty, value);
}
public static EventTriggerCollection GetAttachedTriggers(DependencyObject element)
{
return (EventTriggerCollection)element.GetValue(AttachedTriggersProperty);
}
}
public class EventTriggerCollection : Collection<EventTriggerBehavior>
{
}
<Style x:Name="Test" TargetType="UserControl">
<Setter Property="storeApplication:UiBehaviors.AttachedTriggers">
<Setter.Value>
<storeApplication:EventTriggerCollection>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding LoadedCommand}" />
</core:EventTriggerBehavior>
<core:EventTriggerBehavior EventName="Unloaded">
<core:InvokeCommandAction Command="{Binding UnloadedCommand}" />
</core:EventTriggerBehavior>
</storeApplication:EventTriggerCollection>
</Setter.Value>
</Setter>
</Style>
公共静态类行为
{
public static readonly dependencProperty AttachedTriggersProperty=dependencProperty.RegisterAttached(“AttachedTriggers”、typeof(EventTriggerCollection)、typeof(UiBehaviors)、new PropertyMetadata(null、OnAttachedTriggersChanged));
附加RiggerSchanged上的私有静态无效(DependencyObject d、DependencyPropertyChangedEventArgs e)
{
BehaviorCollection触发器=Interaction.GetBehaviors(d);
如果(e.OldValue!=null)
{
foreach(EventTriggerCollection中的EventTriggerBehavior触发器)e.OldValue
触发器。移除(触发器);
}
如果(e.NewValue==null)
返回;
foreach(EventTriggerCollection中的EventTriggerBehavior触发器e.NewValue)
触发器。添加(触发器);
}
公共静态void SetAttachedTriggers(DependencyObject元素,EventTriggerCollection值)
{
元素设置值(AttachedTriggersProperty,value);
}
公共静态EventTriggerCollection GetAttachedTriggers(DependencyObject元素)
{
return(EventTriggerCollection)元素.GetValue(AttachedTriggersProperty);
}
}
公共类EventTriggerCollection:集合
{
}
我的Xaml如下所示:
public static class UiBehaviors
{
public static readonly DependencyProperty AttachedTriggersProperty = DependencyProperty.RegisterAttached("AttachedTriggers", typeof(EventTriggerCollection), typeof(UiBehaviors), new PropertyMetadata(null, OnAttachedTriggersChanged));
private static void OnAttachedTriggersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BehaviorCollection triggers = Interaction.GetBehaviors(d);
if (e.OldValue != null)
{
foreach (EventTriggerBehavior trigger in (EventTriggerCollection)e.OldValue)
triggers.Remove(trigger);
}
if (e.NewValue == null)
return;
foreach (EventTriggerBehavior trigger in (EventTriggerCollection)e.NewValue)
triggers.Add(trigger);
}
public static void SetAttachedTriggers(DependencyObject element, EventTriggerCollection value)
{
element.SetValue(AttachedTriggersProperty, value);
}
public static EventTriggerCollection GetAttachedTriggers(DependencyObject element)
{
return (EventTriggerCollection)element.GetValue(AttachedTriggersProperty);
}
}
public class EventTriggerCollection : Collection<EventTriggerBehavior>
{
}
<Style x:Name="Test" TargetType="UserControl">
<Setter Property="storeApplication:UiBehaviors.AttachedTriggers">
<Setter.Value>
<storeApplication:EventTriggerCollection>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding LoadedCommand}" />
</core:EventTriggerBehavior>
<core:EventTriggerBehavior EventName="Unloaded">
<core:InvokeCommandAction Command="{Binding UnloadedCommand}" />
</core:EventTriggerBehavior>
</storeApplication:EventTriggerCollection>
</Setter.Value>
</Setter>
</Style>
EventTriggerCollection上需要x:shared=False属性,以便在每次访问属性时创建一组新的触发器。如果没有它,触发器将只对访问属性的第一个控件有效
不幸的是,我无法使用此属性,因为WinRT不支持它。看这个。我现在被卡住了:(我缺少什么?您可以对页面进行子类化,或者在单个属性中定义一个附加属性 例如,对于基本类解决方案: MainPage.xaml
<local:MyAppPageBase
x:Class="App16.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App16"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
LoadedCommand="{Binding LoadedCommand}"
UnloadedCommand="{Binding UnloadedCommand}">
<Grid />
</local:MyAppPageBase>
<Page
x:Class="App16.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App16"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
local:ElementExtensions.LoadedCommand="{Binding LoadedCommand}">
<Grid />
</Page>
MainPage.xaml.cs
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App16
{
public abstract class MyAppPageBase : Page
{
#region LoadedCommand
/// <summary>
/// LoadedCommand Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandProperty =
DependencyProperty.Register(
"LoadedCommand",
typeof(ICommand),
typeof(MyAppPageBase),
new PropertyMetadata(null));
/// <summary>
/// Identifies the LoadedCommand dependency property.
/// </summary>
public static DependencyProperty LoadedCommandProperty { get { return _LoadedCommandProperty; } }
/// <summary>
/// Gets or sets the LoadedCommand property. This dependency property
/// indicates the command to execute when the page loads.
/// </summary>
public ICommand LoadedCommand
{
get { return (ICommand)GetValue(LoadedCommandProperty); }
set { this.SetValue(LoadedCommandProperty, value); }
}
#endregion
#region UnloadedCommand
/// <summary>
/// UnloadedCommand Dependency Property
/// </summary>
private static readonly DependencyProperty _UnloadedCommandProperty =
DependencyProperty.Register(
"UnloadedCommand",
typeof(ICommand),
typeof(MyAppPageBase),
new PropertyMetadata(null));
/// <summary>
/// Identifies the UnloadedCommand dependency property.
/// </summary>
public static DependencyProperty UnloadedCommandProperty { get { return _UnloadedCommandProperty; } }
/// <summary>
/// Gets or sets the UnloadedCommand property. This dependency property
/// indicates the command to execute when the page unloads.
/// </summary>
public ICommand UnloadedCommand
{
get { return (ICommand)GetValue(UnloadedCommandProperty); }
set { this.SetValue(UnloadedCommandProperty, value); }
}
#endregion
public MyAppPageBase()
{
this.Loaded += (s, e) =>
{
if (LoadedCommand?.CanExecute(null) == true)
{
LoadedCommand.Execute(null);
}
};
this.Unloaded += (s, e) =>
{
if (UnloadedCommand?.CanExecute(null) == true)
{
UnloadedCommand.Execute(null);
}
};
}
}
public sealed partial class MainPage : MyAppPageBase
{
public MainPage()
{
this.InitializeComponent();
}
}
}
using System;
using System.Diagnostics;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App16
{
public static class ElementExtensions
{
#region LoadedCommand
/// <summary>
/// LoadedCommand Attached Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandProperty =
DependencyProperty.RegisterAttached(
"LoadedCommand",
typeof(ICommand),
typeof(ElementExtensions),
new PropertyMetadata(null, OnLoadedCommandChanged));
/// <summary>
/// Identifies the LoadedCommand dependency property.
/// </summary>
public static DependencyProperty LoadedCommandProperty { get { return _LoadedCommandProperty; } }
/// <summary>
/// Gets the LoadedCommand property. This dependency property
/// indicates the command to execute when the element loads.
/// </summary>
public static ICommand GetLoadedCommand(DependencyObject d)
{
return (ICommand)d.GetValue(LoadedCommandProperty);
}
/// <summary>
/// Sets the LoadedCommand property. This dependency property
/// indicates the command to execute when the element loads.
/// </summary>
public static void SetLoadedCommand(DependencyObject d, ICommand value)
{
d.SetValue(LoadedCommandProperty, value);
}
/// <summary>
/// Handles changes to the LoadedCommand property.
/// </summary>
/// <param name="d">
/// The <see cref="DependencyObject"/> on which
/// the property has changed value.
/// </param>
/// <param name="e">
/// Event data that is issued by any event that
/// tracks changes to the effective value of this property.
/// </param>
private static void OnLoadedCommandChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ICommand oldLoadedCommand = (ICommand)e.OldValue;
ICommand newLoadedCommand = (ICommand)d.GetValue(LoadedCommandProperty);
if (oldLoadedCommand != null)
{
var handler = GetLoadedCommandHandler(d);
handler?.Detach((FrameworkElement) d);
}
if (newLoadedCommand != null)
{
SetLoadedCommandHandler(d, new LoadedCommandHandler((FrameworkElement)d));
}
}
#endregion
#region LoadedCommandHandler
/// <summary>
/// LoadedCommandHandler Attached Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandHandlerProperty =
DependencyProperty.RegisterAttached(
"LoadedCommandHandler",
typeof(LoadedCommandHandler),
typeof(ElementExtensions),
new PropertyMetadata(null));
/// <summary>
/// Identifies the LoadedCommandHandler dependency property.
/// </summary>
public static DependencyProperty LoadedCommandHandlerProperty { get { return _LoadedCommandHandlerProperty; } }
/// <summary>
/// Gets the LoadedCommandHandler property. This dependency property
/// indicates the object that handles Loaded events on its owning element.
/// </summary>
internal static LoadedCommandHandler GetLoadedCommandHandler(DependencyObject d)
{
return (LoadedCommandHandler)d.GetValue(LoadedCommandHandlerProperty);
}
/// <summary>
/// Sets the LoadedCommandHandler property. This dependency property
/// indicates the object that handles Loaded events on its owning element.
/// </summary>
internal static void SetLoadedCommandHandler(DependencyObject d, LoadedCommandHandler value)
{
d.SetValue(LoadedCommandHandlerProperty, value);
}
#endregion
internal class LoadedCommandHandler
{
public LoadedCommandHandler(FrameworkElement element)
{
element.Loaded += OnLoaded;
}
public void Detach(FrameworkElement element)
{
element.Loaded -= OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var command = GetLoadedCommand((DependencyObject) sender);
if (command?.CanExecute(null) == true)
{
command.Execute(null);
}
}
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new MyViewModel();
}
}
public class MyViewModel
{
public ICommand LoadedCommand { get; private set; } = new MyCommand();
}
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Debug.WriteLine("Blahr");
}
public event EventHandler CanExecuteChanged;
}
}
使用System.Windows.Input;
使用Windows.UI.Xaml;
使用Windows.UI.Xaml.Controls;
名称空间App16
{
公共抽象类MyAppPageBase:页
{
#区域加载命令
///
///LoadedCommand依赖项属性
///
私有静态只读DependencyProperty\u LoadedCommandProperty=
从属属性。寄存器(
“LoadedCommand”,
类型(ICommand),
类型(MyAppPageBase),
新属性元数据(空);
///
///标识LoadedCommand依赖项属性。
///
public static dependencProperty LoadedCommandProperty{get{return}
///
///获取或设置LoadedCommand属性。此依赖项属性
///指示加载页面时要执行的命令。
///
公共ICommand loaded命令
{
get{return(ICommand)GetValue(LoadedCommandProperty);}
set{this.SetValue(LoadedCommandProperty,value);}
}
#端区
#区域未加载命令
///
///UnloadedCommand依赖项属性
///
私有静态只读从属属性\u UnloadedCommandProperty=
从属属性。寄存器(
“未加载的命令”,
类型(ICommand),
类型(MyAppPageBase),
新属性元数据(空);
///
///标识UnloadedCommand依赖项属性。
///
public static dependencProperty UnloadedCommandProperty{get{return{U UnloadedCommandProperty;}}
///
///获取或设置UnloadedCommand属性。此依赖项属性
///指示页面卸载时要执行的命令。
///
公用ICommand未加载的命令
{
获取{return(ICommand)GetValue(unloadedCommand属性);}
set{this.SetValue(UnloadedCommandProperty,value);}
}
#端区
公共MyAppPageBase()
{
此.Loaded+=(s,e)=>
{
if(LoadedCommand?.CanExecute(null)==true)
{
LoadedCommand.Execute(空);
}
};
这个.卸载+=(s,e)=>
{
if(UnloadedCommand?.CanExecute(null)=true)
{
UnloadedCommand.Execute(null);
}
};
}
}
公共密封部分类主页面:MyAppPageBase
{
公共主页()
{
this.InitializeComponent();
}
}
}
附加属性(附加行为)解决方案更为复杂,因为附加属性需要确保它不会导致静态类上的事件订阅导致的泄漏,但它的好处是不需要更改基类,如果您想在多个项目中重用它,这一点尤其有用,可以将其放在NuGet包中:
MainPage.xaml
<local:MyAppPageBase
x:Class="App16.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App16"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
LoadedCommand="{Binding LoadedCommand}"
UnloadedCommand="{Binding UnloadedCommand}">
<Grid />
</local:MyAppPageBase>
<Page
x:Class="App16.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App16"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
local:ElementExtensions.LoadedCommand="{Binding LoadedCommand}">
<Grid />
</Page>
MainPage.xaml.cs
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App16
{
public abstract class MyAppPageBase : Page
{
#region LoadedCommand
/// <summary>
/// LoadedCommand Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandProperty =
DependencyProperty.Register(
"LoadedCommand",
typeof(ICommand),
typeof(MyAppPageBase),
new PropertyMetadata(null));
/// <summary>
/// Identifies the LoadedCommand dependency property.
/// </summary>
public static DependencyProperty LoadedCommandProperty { get { return _LoadedCommandProperty; } }
/// <summary>
/// Gets or sets the LoadedCommand property. This dependency property
/// indicates the command to execute when the page loads.
/// </summary>
public ICommand LoadedCommand
{
get { return (ICommand)GetValue(LoadedCommandProperty); }
set { this.SetValue(LoadedCommandProperty, value); }
}
#endregion
#region UnloadedCommand
/// <summary>
/// UnloadedCommand Dependency Property
/// </summary>
private static readonly DependencyProperty _UnloadedCommandProperty =
DependencyProperty.Register(
"UnloadedCommand",
typeof(ICommand),
typeof(MyAppPageBase),
new PropertyMetadata(null));
/// <summary>
/// Identifies the UnloadedCommand dependency property.
/// </summary>
public static DependencyProperty UnloadedCommandProperty { get { return _UnloadedCommandProperty; } }
/// <summary>
/// Gets or sets the UnloadedCommand property. This dependency property
/// indicates the command to execute when the page unloads.
/// </summary>
public ICommand UnloadedCommand
{
get { return (ICommand)GetValue(UnloadedCommandProperty); }
set { this.SetValue(UnloadedCommandProperty, value); }
}
#endregion
public MyAppPageBase()
{
this.Loaded += (s, e) =>
{
if (LoadedCommand?.CanExecute(null) == true)
{
LoadedCommand.Execute(null);
}
};
this.Unloaded += (s, e) =>
{
if (UnloadedCommand?.CanExecute(null) == true)
{
UnloadedCommand.Execute(null);
}
};
}
}
public sealed partial class MainPage : MyAppPageBase
{
public MainPage()
{
this.InitializeComponent();
}
}
}
using System;
using System.Diagnostics;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App16
{
public static class ElementExtensions
{
#region LoadedCommand
/// <summary>
/// LoadedCommand Attached Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandProperty =
DependencyProperty.RegisterAttached(
"LoadedCommand",
typeof(ICommand),
typeof(ElementExtensions),
new PropertyMetadata(null, OnLoadedCommandChanged));
/// <summary>
/// Identifies the LoadedCommand dependency property.
/// </summary>
public static DependencyProperty LoadedCommandProperty { get { return _LoadedCommandProperty; } }
/// <summary>
/// Gets the LoadedCommand property. This dependency property
/// indicates the command to execute when the element loads.
/// </summary>
public static ICommand GetLoadedCommand(DependencyObject d)
{
return (ICommand)d.GetValue(LoadedCommandProperty);
}
/// <summary>
/// Sets the LoadedCommand property. This dependency property
/// indicates the command to execute when the element loads.
/// </summary>
public static void SetLoadedCommand(DependencyObject d, ICommand value)
{
d.SetValue(LoadedCommandProperty, value);
}
/// <summary>
/// Handles changes to the LoadedCommand property.
/// </summary>
/// <param name="d">
/// The <see cref="DependencyObject"/> on which
/// the property has changed value.
/// </param>
/// <param name="e">
/// Event data that is issued by any event that
/// tracks changes to the effective value of this property.
/// </param>
private static void OnLoadedCommandChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ICommand oldLoadedCommand = (ICommand)e.OldValue;
ICommand newLoadedCommand = (ICommand)d.GetValue(LoadedCommandProperty);
if (oldLoadedCommand != null)
{
var handler = GetLoadedCommandHandler(d);
handler?.Detach((FrameworkElement) d);
}
if (newLoadedCommand != null)
{
SetLoadedCommandHandler(d, new LoadedCommandHandler((FrameworkElement)d));
}
}
#endregion
#region LoadedCommandHandler
/// <summary>
/// LoadedCommandHandler Attached Dependency Property
/// </summary>
private static readonly DependencyProperty _LoadedCommandHandlerProperty =
DependencyProperty.RegisterAttached(
"LoadedCommandHandler",
typeof(LoadedCommandHandler),
typeof(ElementExtensions),
new PropertyMetadata(null));
/// <summary>
/// Identifies the LoadedCommandHandler dependency property.
/// </summary>
public static DependencyProperty LoadedCommandHandlerProperty { get { return _LoadedCommandHandlerProperty; } }
/// <summary>
/// Gets the LoadedCommandHandler property. This dependency property
/// indicates the object that handles Loaded events on its owning element.
/// </summary>
internal static LoadedCommandHandler GetLoadedCommandHandler(DependencyObject d)
{
return (LoadedCommandHandler)d.GetValue(LoadedCommandHandlerProperty);
}
/// <summary>
/// Sets the LoadedCommandHandler property. This dependency property
/// indicates the object that handles Loaded events on its owning element.
/// </summary>
internal static void SetLoadedCommandHandler(DependencyObject d, LoadedCommandHandler value)
{
d.SetValue(LoadedCommandHandlerProperty, value);
}
#endregion
internal class LoadedCommandHandler
{
public LoadedCommandHandler(FrameworkElement element)
{
element.Loaded += OnLoaded;
}
public void Detach(FrameworkElement element)
{
element.Loaded -= OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var command = GetLoadedCommand((DependencyObject) sender);
if (command?.CanExecute(null) == true)
{
command.Execute(null);
}
}
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new MyViewModel();
}
}
public class MyViewModel
{
public ICommand LoadedCommand { get; private set; } = new MyCommand();
}
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Debug.WriteLine("Blahr");
}
public event EventHandler CanExecuteChanged;
}
}
使用系统;
使用系统诊断;
使用System.Windows.Input;
使用Windows.UI.Xaml;
使用Windows.UI.Xaml.Controls;
名称空间App16
{
公共静态类ElementExtensions
{
#区域Lo