【问题标题】:Bind to current item in ItemsControl (WP7.1 / 8.0 / Silverlight)绑定到 ItemsControl 中的当前项目 (WP7.1 / 8.0 / Silverlight)
【发布时间】:2013-03-09 20:38:24
【问题描述】:

Windows Phone 7.1 项目(WP 8.0 SDK),我想将 ItemTemplate 中的当前项传递给用户控件。

XAML:

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:ShipControl Ship="{Binding}"  x:Name="ShipControl"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>

ShipControl 背后的代码:

public object Ship 
    {
        get
        {
            return GetValue(ShipProperty);
        }
        set
        {
            SetValue(ShipProperty, value);
        }
    }

    //Used by xaml binding
    public static readonly DependencyProperty ShipProperty = DependencyProperty.Register("Ship", typeof(Ship), typeof(Ship), new PropertyMetadata(null, new PropertyChangedCallback(OnShipChanged)));

    private static void OnShipChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        //TODO: Set break point here

        return;
    }

但是,在调试 Ship 时,值 DataBinding 的对象作为值传递,而不是 Ship(因此返回类型是 object 而不是 Ship)。这最终会导致 SetValue 出现异常。 Ship-properties 上的其他绑定确实有效,所以我真的不知道。根据这个问题,上面应该可以工作:

WPF Pass current item from list to usercontrol

有关在数据绑定上引发异常的示例项目,请参见此处,因为传递的对象是绑定而不是数据对象。 http://dl.dropbox.com/u/33603251/TestBindingApp.zip

【问题讨论】:

    标签: silverlight windows-phone-7 windows-phone-8


    【解决方案1】:

    您需要将x:Name="MyControl" 放在您的控件中,然后您的绑定将看起来像Ship="{Binding ElementName=MyList, Path=CurrentItem}" 而不仅仅是{Binding}(这并不意味着太多AFAIK)。您的控件需要公开CurrentItem 属性。

    如果您不想明确命名您的控件,您可以尝试使用Relative Source,但我自己没有尝试,所以无法帮助您。

    【讨论】:

    • {Binding} 是我在其他一些网站上看到的,比如我引用的链接:stackoverflow.com/questions/3106190/… 我稍后会试一试,谢谢。
    • 请进一步解释。我必须在后面的代码中添加一个属性,但它应该返回什么?我在数据项可用的 ItemsControl 的 ItemTemplate 中,所以我不明白为什么我必须添加代码隐藏。我只想获取当前数据项。在 ASP.Net 中这很容易,为什么在 WPF / SL 中这么难...
    【解决方案2】:

    您的依赖属性格式错误,因此 XAML 解析器不会这样对待它。

    您需要将您的实例属性类型更改为 Ship,并将 DependencyProperty 所有者类型更改为 ShipControl。然后绑定将起作用(假设您绑定到船舶列表)。

    public Ship Ship
    {
        get { return (Ship)GetValue(ShipProperty); }
        set { SetValue(ShipProperty, value); }
    }
    
    public static readonly DependencyProperty ShipProperty =
        DependencyProperty.Register("Ship", typeof(Ship), typeof(ShipControl), new PropertyMetadata(null, new PropertyChangedCallback(OnShipChanged)));
    
    private static void OnShipChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        //TODO: Set break point here
    
        return;
    }
    

    【讨论】:

    • 不起作用,在示例项目中尝试过。我得到一个 COM 异常,因为传递给 Ship 的对象不是 Ship 类型。如果我将其更改为对象,我可以看到 Ship_set 中的“值”是 Binding 类型而不是 Ship 类型。
    • 听起来 DP 确实有效,并且您的 XAML 绑定不正确。您可以发布您将 ItemsControl 的 ItemsSource 绑定到的集合吗?
    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多