在Silverlight中将文本框的DataContext设置为当前类

3

我在一个用户控件中有一个文本框,我创建了一个属性,在用户控件中想要将文本框的文本属性绑定到所创建的属性。

问题在于我不知道如何在XAML中将数据上下文指定为当前类。

有什么办法吗?谢谢。

2个回答

2

这将把您在文本框中输入的内容传递到代码后台的属性中。根据项目大小,我建议使用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;
    }
 }

0

我会在代码中创建绑定。假设您的文本框具有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 属性留待其他更典型的用途。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接