我的项目中有两个 Silverlight 控件,它们都有属性 TeamId。我想在托管两个用户控件的控件中的 XAML 中将它们绑定(bind)在一起,类似于:
<agChat:UserTeams x:Name="oUserTeams" />
<agChat:OnlineUser x:Name="oOnlineUsers" TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" />
在第一个控件中,我正在实现 System.ComponentModel.INotifyPropertyChanged 并在 TeamId 属性更改时引发 PropertyChanged 事件。
在第二个控件中,我使用 propdp 片段将 TeamId 标识为依赖属性。
// 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 绑定(bind)到元素。
这是违规行: TeamId="{Binding ElementName=oUserTeams, Path=TeamId}"
特别是元素名称
如果可以,将数据对象放入 Resources 并在那里声明它,那么您可以这样做:
<agChat:UserTeams x:Name="oUserTeams"
DataContext="{StaticResource myDataObject}" />
<agChat:OnlineUser x:Name="oOnlineUsers"
DataContext="{StaticResource myDataObject}"
TeamId="{Binding TeamId}" />
关于silverlight - Silverlight 中的自定义属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355/