【问题标题】:Silverlight UserControl BindingSilverlight 用户控件绑定
【发布时间】:2010-12-20 13:20:57
【问题描述】:

我有一个简单的用户控件

Xaml:

<UserControl x:Class="GraemeGorman_Controls.Navigation.NavigationItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Border x:Name="borderLayoutRoot">
        <TextBlock x:Name="textBlockCaption" Text="{Binding Caption}" />
    </Border>
</UserControl>

Cs:

namespace GraemeGorman_Controls.Navigation
{
    public partial class NavigationItem : UserControl
    {
        public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register(
            "Caption",
            typeof (string),
            typeof (NavigationItem),
            new PropertyMetadata(new PropertyChangedCallback(OnCaptionChanged)));

        public string Caption
        {
            get {return (string)GetValue(CaptionProperty);}
            set {SetValue(CaptionProperty, value);}
        }

        public NavigationItem()
        {
            InitializeComponent();
        }

        private static void OnCaptionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //null
        }
    }
}

我的问题是,当我创建一个控件实例时,标题永远不会显示 - 现在我已经使用 e.NewValue 测试了 OnCaptionChanged 函数中的属性,它是正确的值。我的绑定有什么问题?

如果我在 set 的标题属性后面写代码

textBlockCaption.Text = value;

看起来不错……

任何帮助表示赞赏

谢谢 格雷姆

【问题讨论】:

    标签: c# wpf silverlight binding user-controls


    【解决方案1】:

    从后面的代码看来,您缺少一行代码。

    尝试在构造函数中添加DataContext = this;。这在过去对我有用。

    【讨论】:

    • 如果你修改了DataContext,你将无法使用更高一级的数据绑定(在使用UserControl的表单上)
    【解决方案2】:

    您如何创建 NavigationItem 控件的实例?

    您需要执行以下操作:

    <Page ...
      xmlns:gg="clr-namespace:GraemeGorman_Controls.Navigation">
    
    <gg:NavigationItem Caption="FooBar" />
    

    甚至

    <gg:NavigationItem Caption="{Binding Path=TheCaption}" />
    

    TheCaption 是您页面的 DataContext 的一个属性(例如您的 ViewModel)

    希望这会有所帮助:)

    【讨论】:

    • 是的,我就是这样创建控件的!
    猜你喜欢
    • 2013-03-30
    • 2011-05-21
    • 2011-10-13
    • 1970-01-01
    • 2011-11-22
    • 2012-03-03
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多