如何在Silverlight 4中的代码中附加EventTrigger

时间:2010-08-30 11:53:28

标签: silverlight-4.0

我的问题如下:

我有一个网格,我在xaml文件中以下列方式附加了SelectedIndexChanged事件:

"<cc:DetailViewGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="0,0,0,0" Name="dgAcitivityList" VerticalAlignment="Stretch" ItemsSource="{Binding EntityList}" SelectionMode="Single" IsReadOnly="False">
            <interactivity:Interaction.Triggers>
                <interactivity:EventTrigger EventName="SelectionChanged">
                    <interactivity:InvokeCommandAction Command="{Binding SelectedItemChangeCommand}" CommandParameter="{Binding SelectedItem, ElementName=dgAcitivityList}"/>
                </interactivity:EventTrigger>
            </interactivity:Interaction.Triggers>"

但我想在代码中附加此事件。我处理了一个从windows网格继承的自己的网格,我把这个代码放在了自己的控制之下。

   public override void OnApplyTemplate()
        {
            //base.OnApplyTemplate();

            System.Windows.Interactivity.EventTrigger selectedItemChangedTrigger = new System.Windows.Interactivity.EventTrigger("SelectionChanged");

            System.Windows.Interactivity.InvokeCommandAction action = new System.Windows.Interactivity.InvokeCommandAction();

            action.CommandName = "{Binding SelectedItemChangeCommand}";

            action.CommandParameter = string.Format("{{Binding SelectedItem, ElementName={0}}}", this.Name);

            selectedItemChangedTrigger.Actions.Add(action);

            System.Windows.Interactivity.Interaction.GetTriggers(this).Add(selectedItemChangedTrigger);

            base.OnApplyTemplate();
        }

此解决方案是否合适?它不起作用,但我不确定是否应该将此代码放在OnApplyTemplate()方法中。

0 个答案:

没有答案