silverlight - Silverlight 中的自定义属性绑定(bind)

标签 silverlight

我的项目中有两个 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/

相关文章:

javascript - 我可以/应该使用哪些 HTML/CSS/JS 库来获得类似的 XAML 功能?

flash - 用户到用户音频通信的最佳方法

c# - 在 Silverlight 中使用 DataForm 中的密码文本框

c# - 如何以阻塞/同步方式下载文件?

wpf - Visual Studio 2010 WPF/Silverlight 设计器默认背景

c# - 从子程序集中读取父 Silverlight 项目的文件夹结构

silverlight - Windows Phone 7 - 使用应用程序栏和 Prism(或 MVVM)

silverlight - 复选框无法在xaml中设置初始值?

visual-studio-2008 - 在 XAML 中创建具有代码完成功能的属性或 DependencyProperties

c# - silverlight动画不工作