【问题标题】:How to bind to the method defined in the data source class?如何绑定到数据源类中定义的方法?
【发布时间】:2012-04-02 18:16:08
【问题描述】:

我有一个作为数据源的对象列表。类似的东西:

public class DataList
{
     public List<DataItem> SomeItems;
     public void RemoveItem(DataItem item)
     {
         SomeItems.Remove(item);
     }
}

非常简单。 现在我有一个引用此数据源的 XAML。类似的东西:

<layout:Accordion ItemsSource="{Binding SomeItems}" SelectionMode="ZeroOrMore" HorizontalAlignment="Stretch" 
ItemTemplate="{StaticResource SomeItemTemplate}">
...

SomeItemTemplate 模板在 App.xaml 中定义的位置

<DataTemplate x:Key="SomeItemTemplate">
<Grid>
..
<Button Command={?} Content="Remove" CommandParameter="{Binding}">


</DataTemplate>

如何绑定命令以引用 DataList.RemoveItem?这个想法是将项目传递给知道一切的父类(DataList)。我可以在 DataItem 类本身中定义此方法(删除),但在这种情况下,我需要(在构造函数中)传递父类,因为项目对父类一无所知。

找到解决方案。请参阅此处 (http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource%28v=vs.95%29.aspx)

使用 &lt;Button x:Name="btnDeleteItem" Command="{Binding DataContext.RemoveItemCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"

【问题讨论】:

    标签: silverlight binding silverlight-5.0


    【解决方案1】:

    如果您使用的是 silverlight 5,则可以使用 RelativeSource 绑定:

    <Button Command="{Binding DataContext.RemoveItemCommand, RelativeSource={RelativeSource AncestorLevel=2}}"/>
    

    这个想法是在层次结构中找到更高层次的可视元素并将其作为 dataContext (DataList)。

    【讨论】:

    • 谢谢。如果我尝试你的方式,我会遇到异常“{System.InvalidOperationException: AncestorType must be set when RelativeSource.Mode is set to FindAncestor. at System.Windows.Data.RelativeSource.System.ComponentModel.ISupportInitialize.EndInit() at MS.Internal .FrameworkCallbacks.SupportInitializeEndInit(IntPtr nativeTarget)}”。这是什么意思?
    • 这意味着您需要指定要查找的祖先类型。在你的情况下,它是手风琴。这样的事情应该没问题:RelativeSource={RelativeSource AncestorType={x:Type local:Accordion}}
    • 谢谢,我使用
    • 不客气 :) 要么是您的 UserControl 具有相同的 DataContext,要么是 Accordion 从 UserControl 继承,或者运行时以某种方式遍历树以搜索 dataContext 不为空的继承成员。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2010-10-02
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2013-02-13
    相关资源
    最近更新 更多