【问题标题】:How to add Command to ListBox.ItemTemplate如何将命令添加到 ListBox.ItemTemplate
【发布时间】:2013-04-10 14:46:12
【问题描述】:

我有一个使用 MVVM 的 WPF 应用程序。

此代码来自我的 ResourceDictionary.xaml

  <DataTemplate x:Key="LogListTemplate">
        <ListBox ItemsSource="{Binding LogList, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource HorizontalListBoxItem}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource ErrorBorders}">
                        <StackPanel ToolTip="{Binding Details}" Width="250">
                            <TextBlock Text="{Binding Title}" />
                            <TextBlock Text="{Binding Details}" TextWrapping="Wrap" />
                            <Button Command="{Binding AddToTempDtdFileCommand}" CommandParameter="{Binding Details}" Content="Ignore" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DataTemplate>

当我单击 Button 时,该命令不执行。测试证实这是因为我的 Button 位于 ListBox 中。

我的问题是我无法将按钮移出 ListBox 有两个原因。

1. Asthetics/UI (the button has belong with the information)  
2. Binding to the LogList is done from within the ListBox.ItemTemplate  

大家有什么建议吗?

【问题讨论】:

    标签: xaml binding command


    【解决方案1】:

    如果命令在ViewModel 中定义,您可以使用RelativeSource 访问它。 RelativeSource 可以找到一个祖先(即您的View),因此您可以使用它的DataContext(您的ViewModel)。

    <Button Command="{Binding DataContext.AddToTempDtdFileCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourViewClass}}}" CommandParameter="{Binding Details}" Content="Ignore" />
    

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      相关资源
      最近更新 更多