我的项目中有两个Silverlight控件,都有属性TeamId。我想将这些绑定在XAML中的控件托管两个用户控件类似于:

        <agChat:UserTeams x:Name="oUserTeams" />
        <agChat:OnlineUser x:Name="oOnlineUsers" TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" />

在第一个控件中,我正在实现System.ComponentModel.INotifyPropertyChanged并在TeamId属性更改时引发PropertyChanged事件。

在第二个控件中,我使用了propdp片段将TeamId标识为Dependency属性。

        // Using a DependencyProperty as the backing store for TeamId.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TeamIdProperty = 
        DependencyProperty.Register(
        "TeamId", 
        typeof(string), 
        typeof(OnlineUsers), 
        new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged)));

然而,当第一次创建silverlight控件时,我从Silverlight获得了以下异常:

 Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

任何想法我做错了什么?显然这可以在代码隐藏中完成,但这个似乎就像正确的方法。

有帮助吗?

解决方案

这是WPF中的正确方法,但不是Silverlight中的方法。

您无法在Silverlight中使用xaml绑定到元素。

这是违规行:  TeamId =&quot; {Binding ElementName = oUserTeams,Path = TeamId}&quot;

特别是ElementName

如果可以,将数据对象放入参考资料并在那里声明,然后你可以这样做:

<agChat:UserTeams x:Name="oUserTeams" 
       DataContext="{StaticResource myDataObject}" />
<agChat:OnlineUser x:Name="oOnlineUsers" 
       DataContext="{StaticResource myDataObject}" 
       TeamId="{Binding  TeamId}" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top