【问题标题】:CheckBox [Inside ListBox ItemTemplate] Checked Event is not triggeringCheckBox [Inside ListBox ItemTemplate] Checked 事件未触发
【发布时间】:2013-02-08 13:42:21
【问题描述】:

这是我的xaml

    <ListBox x:Name="HistoryList"          
                     ItemsSource="{Binding HistoryCollection}" 
                       >
        <ListBox.ItemTemplate >
            </DataTemplate>                 
                    <CheckBox x:Name="UpCheckBox"   Height="50" Width="50" >
                        <interactivity:Interaction.Triggers>
                            <interactivity:EventTrigger EventName="Checked">
                                <interactivity:InvokeCommandAction Command="{Binding UpCheckedCommad}" CommandParameter="{Binding ElementName=UpCheckBox}"></interactivity:InvokeCommandAction>
                            </interactivity:EventTrigger>
                        </interactivity:Interaction.Triggers>
                    </CheckBox>                 
            </DataTemplate>
        </ListBox.ItemTemplate >
    </ListBox >

ViewModel我用过GalasoftMVVM Command Binding

    public ICommand UpCheckedCommad
    {
        get { return new RelayCommand<Object>(x => { PerformUpforTracks(x); }); }
    }

    void PerformUpforTracks(object x)
    {
        //TODO 
    }

我在ListBox ItemTemplate 中使用了CheckBox。但在ViewModel 中没有得到CheckBoxChecked 事件。
我想从我的 ViewModel 中获取 Checked Event。
任何人都可以解决这个问题吗?

【问题讨论】:

    标签: c# silverlight windows-phone-7 xaml windows-phone-8


    【解决方案1】:

    ListBox.ItemTemplate 的每个实例都被自动赋予“集合中的当前项”作为其 DataContext。在您的情况下,这是 HistoryCollection 中的每个单独项目。在您的示例中,EventTrigger 正在您当前的 HistoryItem 实例中搜索“ThumbsUpCheckedCommad”。

    为了强制 EventTrigger 在您想要的 ViewModel 中进行搜索,您需要指定命令绑定的“Source”属性。我建议使用 RelativeSource 语法,在树上搜索最后一个控件,以将您的 ViewModel 作为其 DataContext。

    它看起来像这样。

    {Binding Path=ThumbsUpCheckedCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}
    

    【讨论】:

    • 你能告诉我命名空间属于'x'吗?
    • 您已经在代码示例中使用了“x”命名空间。它是 XAML 架构的内置命名空间。 “AncestorType={x:Type ListBox}”基本上只是说“向上移动树,直到我们找到一个 ListBox,然后在它的 DataContext 中查找我的 Binding。”
    • 感谢老兄的帮助。我得到了答案。无论如何我没有从'x'获取类型。我不知道为什么会这样。
    • 祖先绑定没有找到目标类型的DataContext,它只找到该类型的第一个实例。此外,Silverlight 5 添加了祖先绑定,但在 WP7 中不可用。对于 Silverlight,您的 RelativeSource 语法也不正确。 Binding 的格式应如下所示:{Binding Path=DataContext.ThumbsUpCheckedCommand, RelativeSource={RelativeSource AncestorType=ListBox}}
    • 你提出了很多观点,@TriggerPin。你有编辑权限吗?因为据我所知,如果您只是通过几次编辑使答案正确,我会更有建设性!答案的本质还是一样的;他正在错误的 DataContext 中寻找命令绑定。
    【解决方案2】:

    我通过这种方式绑定Command得到它

    Command="{Binding Path=DataContext.UpCheckedCommad,
              ElementName=HistoryList}" 
    

    【讨论】:

      猜你喜欢
      • 2012-04-09
      • 1970-01-01
      • 2017-06-09
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多