WPF中的用户控件绑定 [英] User control binding in wpf

查看:77
本文介绍了WPF中的用户控件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个问题,如果有人可以帮助我解决问题,那就是.
我有一个用户控件,它是圆形文本框",仅由一个文本框组成,
我确实写了几行代码来绑定此用户控件,但是它起作用了,但是如果我更改source属性,则以一种方式将舍入的文本框显示为修改,如果我从文本框中更改,则更改不会出现在属性限制内;
圆形文本框后面的代码是:

Hi,
I have a problem if any one can help me to solve it, the problem is.
i have a user control it is Rounded Text Box,composed from one text box only,
i did write some line of code to can bind this user control,it is worked but in one way if i change the source property the rounded text box show the modification by if i change from the text box the change do not appear in property bounded;
the code behind of rounded text box is :

public partial class  UCRTextBox : UserControl
{
  public static readonly DependencyProperty TextProperty = DependencyProperty.Register
  ("Text",typeof(string),typof(UCRTextBox), new FrameworkPropertyMetadata  
  (null,FrameworkMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallBach(textChangedCallBack),
  new CoerceValueCallback(coerceValue)));

  public string Text
  {
      get{return (string)GetValue(TextProperty);}
      set{SetValue(TextProperty,value);}
  }

  static void textChangedCallBack(DependencyObject property,DependencyPropertyChangedEventsArgs args)
  {
      UCRTextBox ucRounded=(UCRTextBox)property;
      ucRounded.TextBx.text=(string)args.NewValue;
  }

  static object CoerceValue(DependencyObject sender,object value)
  { 
      return (string)value;
  }

}



我在窗口中的代码确实使用了此控件,但确实通过后面的代码将其绑定了:



and the code in the window with i did use this control i did bind it by code behind:

private void SetTextBoxBinding(FrameworkElement target,DependencyProperty dp,string value)
{
   Binding b=new Binding(value);
   b.source=_editPatient.Patient;
   b.Mode=BindingMode.TwoWay;
   target.SetBinding(dp,binding);
}



用于此功能的是:

在窗口上加载事件



Using for this function is :

on the windowLoad Events

this.SetTextbinding(this.txtFirstName,TextBox.TextProperty,"FirstName");




就这些 .

任何人都可以向我展示解决此问题的正确方法吗?
和表示所有




that is all .

can any one show me the correct way to solve this problem??
and thx for all

推荐答案

为什么不从XAML设置Binding?

UserControl的XAML中,可以将TextBoxText属性绑定到UserControlText属性,如下所示:

In your UserControl''s XAML you can bind the Text property of the TextBox to the Text property of the UserControl, like the following:

<TextBox x:Name="TextBx"

            Text="{Binding Text, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />

在使用UserControl的窗口中,您可以绑定UserControlText属性,如下所示:

In the window that uses the UserControl you can bind the Text property of the UserControl, like the following:

<ucNamespace:UCRTextBox x:Name="TextBx"

         Text="{Binding MyProperty, Mode=TwoWay}" />

别忘了设置 DataContext 适当的窗口. :)

Don''t forget to set the DataContext of the window appropriately. :)


这篇关于WPF中的用户控件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆