【问题标题】:Binding to View Model Property from within ItemsControl.ItemTemplate从 ItemsControl.ItemTemplate 绑定到视图模型属性
【发布时间】:2011-05-22 04:05:59
【问题描述】:

我的 ViewModel 中有一组对象和一个命令。

我想为集合中的每个对象显示一个超链接,并将每个超链接的 Command 设置为相同的命令,将 objectID 作为 CommandParemeter 传递。例如

// View Model
public class MyViewModel : ViewModelBase
{
  // Raises PropertyChanged event, ommited here
  public List<MyClass> MyList {....}

  public RelayCommand<int> MyCommand {....}
}

我将 UserControl 的 DataContext 设置为上述 ViewModel 类。此 UserControl 的 XAML 如下:

<UserControl>
  <ItemsControl ItemsSource="{Binding Path=MyList}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel />
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <HyperlinkButton Content="{Binding Path=Description}" Command="{Binding Path=MyCommand}" CommandParameter="{Binding Path=MyClassID}"/>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</UserControl>

超链接内容的描述显示正确,但命令从不触发,我猜这是因为它在 MyClass 对象中寻找命令?

如何绑定到 UserControls DataContext.MyCommand 而不是它正在寻找的 MyClass.MyCommand?

【问题讨论】:

    标签: silverlight data-binding xaml silverlight-4.0


    【解决方案1】:

    不幸的是,我们在 WPF 具有的 RelativeSource 标记扩展上没有 FindAncestor 模式,因此您不能使用它(这将在 Silverlight 5 中添加)。这很讨厌,但您可以为您的 UserControl 元素命名,并使用 ElementName 绑定绑定到分配给其 DataContext 的对象上的命令。

    例如:

    <UserControl Name="root">
    

    然后绑定命令(使用来自 UserControl 的 DataContext 的点表示法):

    Command="{Binding Path=DataContext.MyCommand, ElementName=root}"
    

    试试看。

    【讨论】:

    • 克里斯 我和费尔明有同样的问题。我正在使用 SL 5,RelativeSource 绑定不起作用,您的答案也不起作用。顺便说一句,由于 DataContext 没有名为 MyCommand 的属性,我看不出你的答案是如何工作的。在我的视图(即 root)中,我在 getter 中有一个名为 ViewModel 的属性,我这样做:返回(MyViewModel)DataContext。还是不行。
    • 嗨 Sam,MyCommand 与 Fermin 提供的示例有关 - 他的视图模型上的命令。不幸的是,我没有足够的关于您的问题的详细信息来帮助您。您最好开始一个新问题,详细说明您正在尝试做什么以及如何尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2013-03-22
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多