0
要綁定「裝」和「卸載」我使用下面的代碼在我的XAML頁面事件:如何重用互動行爲中的XAML的WinRT應用與MVVM架構
<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>
一切正常不過,我將這些相同的代碼複製到每個視圖中?我怎樣才能使這個可重用?
EDIT
我創建使用的代碼在此post附加屬性。
我的附加屬性是這樣的:
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>
{
}
我的XAML看起來是這樣的:
<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>
的X:共享=需要在EventTriggerCollection假屬性創建一個新的組觸發器每次訪問該屬性。沒有它,觸發器只能用於訪問屬性的第一個控件。
不幸的是,我無法使用此屬性,因爲它在WinRT中不受支持。看到這個post。我現在堅持:(我缺少什麼
感謝您的回覆。我試圖定義一個沒有太多運氣的附屬財產。看到我編輯的帖子。你有沒有一個「Sub Classing」Xaml頁面的例子? –
@CoolBreeze更新了我的答案。 –
謝謝你們兩個例子。我更喜歡附加的行爲解決方案:) –