【问题标题】:Set DataContext of a textbox to the current class in silverlight在silverlight中将文本框的DataContext设置为当前类
【发布时间】:2010-02-10 16:53:19
【问题描述】:

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

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

有什么想法吗??谢谢

【问题讨论】:

    标签: silverlight silverlight-3.0 silverlight-4.0 datacontext bindingsource


    【解决方案1】:

    这会将您在文本框中输入的内容保存到代码隐藏中的属性中。根据您项目的大小,我会考虑使用 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;
        }
     }
    

    【讨论】:

      【解决方案2】:

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

        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-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        • 2018-03-12
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多