Set the DataContext of the text field for the current class to silverlight

I have a text field in UserControl, I created a property in UserControl, I want to bind the text property textbox to the property created in usercontrol.

The problem is that I do not know how to define the datacontext for the current class in XAML.

Any idea ?? thank

+3
source share
2 answers

, , . MVVM, ViewModel, UserControl this.DataContext = 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>

:

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

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

. , TextBox x:Name="MyTextBox" , (, , INotifyPropertyChanged), MyText .

  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);
   }
 }

UserControl DataContext .

+1

Source: https://habr.com/ru/post/1732217/


All Articles