3

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

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

任何的想法??谢谢

4

2 回答 2

2

这会将您在文本框中输入的内容保存到代码隐藏中的属性中。根据您项目的大小,我会考虑使用 MVVM 将代码推送到 ViewModel,然后在 UserControl 中指定 this.DataContext = ViewModel 的实例。

xml:

<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;
    }
 }
于 2010-02-10T17:14:12.493 回答
0

我会在代码中创建绑定。假设您的 TextBox还假设您已经添加了在您的用户控件上调用x:Name="MyTextBox"的依赖属性(或至少是具有实现的标准属性)。INotifyPropertyChangedMyText

  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属性为其他更典型的用途打开。

于 2010-02-11T11:37:36.450 回答