如何为usercontrol设置数据绑定?

时间:2012-07-20 10:50:06

标签: c# wpf data-binding user-controls dependency-properties

我的项目,我想使用一个用户控件,它是文本块和文本框的组合。我可以为用户控件创建一些自定义属性,如

  public string Caption
    {
        get
        {
            return this.Block.Text;
        }
        set
        {
            this.Block.Text = value;
        }
    }

    public string Value
    {
        get
        {
            return this.Box.Text;
        }
        set
        {
            this.Box.Text = value;
        }
    }

我还想在此usercontrol中设置textblock的绑定。我知道我们必须使用依赖属性,如下所示:

  public string fieldValue
    {
        get
        {
            return (string)GetValue(fieldValueProperty);
        }
        set
        {
            SetValue(fieldValueProperty, value);
        }
    }          
    public static readonly DependencyProperty fieldValueProperty =
        DependencyProperty.Register("fieldValue", typeof(string), typeof(TextBlox), 
        new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); 

在我的实际应用中:

  <my:TxtBlox HorizontalAlignment="Left" Name="txtBlox1"                      
                 fieldValue="{Binding Path=ProdCode,Mode=TwoWay}"
                 VerticalAlignment="Top" Width="228" />

我正在将此控件的容器的datacontext设置为数据库对象。

 oProd = dt.ProdInfoes.First();
        Main.DataContext = oProd;

但是我无法让它发挥作用。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

如果要绑定它们,则必须创建DependencyProperties CaptionValue而不是普通属性。在您的usercontrol xaml中,您必须使用ElementName绑定设置绑定到属性。见this帖子

相关问题