开发者

Set DataContext of a textbox to the current class in silverlight

开发者 https://www.devze.com 2022-12-19 15:19 出处:网络
i have a textbox in a UserControl, 开发者_JAVA技巧 i created a property in the UserControl, i want to bind the textbox text property to the property created in the usercontrol.

i have a textbox in a UserControl, 开发者_JAVA技巧 i created a property in the UserControl, i want to bind the textbox text property to the property created in the usercontrol.

The problem is that i dont know how to especify the datacontext to the current class in XAML.

Any idea?? thanks


This will get what you enter in your textbox to your property in the codebehind. Depending on the size of your project I'd consider MVVM to push the code out to the ViewModel, then in the UserControl you'd specify this.DataContext = an instance of your ViewModel.

Xaml:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <StackPanel>

        <TextBox Text="{Binding Foo,Mode=TwoWay}"/>

        <Button Content="Click" Click="Button_Click"/>

    </StackPanel>

</UserControl>

Code Behind:

 public partial class MainPage : UserControl
 {
    public string Foo { get; set; }

    public MainPage ()
    {
      InitializeComponent();
      this.DataContext = this;
    }
 }


I would create the binding in code. Assume your TextBox has x:Name="MyTextBox" also assume you've added a dependency property (or at least a standard property with INotifyPropertyChanged implementation) called on MyText on your user control.

  public partial class MainPage : UserControl
  {
   public MainPage ()
   {
     InitializeComponent();
     Binding binding = new Binding("MyText");
     binding.Mode = BindingMode.TwoWay;
     binding.Source = this;
     MyText.SetBinding(TextBox.TextProperty, binding);
   }
 }

This leaves the UserControl's DataContext property open for other more typical uses.

0

精彩评论

暂无评论...
验证码 换一张
取 消