【问题标题】:How to connect a Button in a Silverlight ListItem DataTemplate, in a ResourceDictionary (Styles.xaml), with a handler?如何将 ResourceDictionary (Styles.xaml) 中 Silverlight ListItem DataTemplate 中的按钮与处理程序连接起来?
【发布时间】:2010-01-22 15:45:33
【问题描述】:

好的,所以情况是我正在为 ResourceDictionary (Styles.xaml) 中的 ListBox 定义一个 ItemTemplate。 ListBoxItem 模板如下所示:

<ControlTemplate TargetType="ListBoxItem">
    <Button Command="{Binding Path=DoSomeCommand}" Content="Test"  />
</ControlTemplate>

现在无论在何处使用此模板,我都希望将此按钮的单击绑定到可用的 ViewModel 命令来处理它。

但是这不起作用,我也试过这个:

<ControlTemplate TargetType="ListBoxItem">
    <Button Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DoSomeCommand}" Content="Test"  />
</ControlTemplate>

但还是没有骰子。

一个有效的简单示例是,如果您在使用它的控件(资源)中定义模板,并且只使用事件处理程序(所有生成的 XAML 的处理程序相同。

关于实现此目的的最佳方法有什么想法或想法吗?我认为这一定是一个常见的场景:目标只是让用户与 ListBox 中的项目进行交互。

谢谢!

【问题讨论】:

    标签: silverlight xaml


    【解决方案1】:

    好的,我想我已经回答了我自己的问题:

    解决方案似乎是在此处使用 'nested' ViewModels

    换句话说,我没有让我的 ListBox 直接绑定到 DTO/业务对象的集合(就像我在上面所做的那样),而是创建了一个简单的 ViewModel 来包装每个 DTO,并在 it,而不是在原始的顶级 VM 上。

    所以绑定的集合现在看起来像这样:

        TestItems = new ObservableCollection<ItemVM> ()
        {
            new ItemVM(),
            new ItemVM(),
            new ItemVM()
        };
    

    每个ItemVM只是包装了DTO,并有命令:

    public class ItemVM : INotifyPropertyChanged
    {
        public ItemVM ()
        {
            this.MyCommand = new DelegateCommand<string> ( TheCommand );
        }
    
        public ICommand MyCommand { get; private set; } 
        public MyBusinessObject BizObj;
    }
    

    瞧,不需要RelativeSource,我们有一个包含命令的可重用模板。

    【讨论】:

      【解决方案2】:

      长答案:Reference to a TextBox inside a DataTemplate

      简答:使用 Prism 命令或混合行为。

      【讨论】:

      • 谢谢贾斯汀,但是我认为在上面的代码示例中很清楚我正在使用命令(实际上命令现在已内置到 Silverlight 框架中,不再需要使用 Prism 附加行为)。我认为问题在于每个 ListItem 的 DataContext 成为数据绑定列表中的对象,而不是“页面”ViewModel。这就是为什么我希望新的 TemplatedParent RelativeSource 可以提供帮助..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 2011-08-22
      • 1970-01-01
      相关资源
      最近更新 更多