如何将TextBox数据绑定到代码背后的属性

时间:2010-08-22 17:50:56

标签: wpf silverlight expression-blend blend

我正在使用Expression Blend。

让我说我得到了:

Public string FirstName{get;set;}

编辑:感谢您的回答,但我担心人们不理解我的问题。我知道如何在代码或XAML中绑定数据。

我的问题是,如果有一种方法可以使用Expression Blend Interface完成所有操作而无需直接编写它。只有鼠标移动。

2 个答案:

答案 0 :(得分:5)

您实际上希望将该属性放在View Model上,并使用XAML绑定,但这是另一个故事。

在描述您的示例时,您首先需要将“FirstName”属性实现为依赖项属性,而不是简单的get / set。 Here is a great code-snippet from Shawn Wildermuth以节省大量输入(您需要修复的代码段中只有一个拼写错误 - “($ type $)args。 NewValue ;”... NewValue有错误的情况在摘录中。)

您可以在XAML中绑定到一个简单的get / set属性,但它是单向/一次性绑定,不会随更改而更新。

在代码中,绑定需要设置两件事。

  • 设置控件(或页面)的DataContext和
  • 在控件上设置数据绑定。

对于您提到的示例,您可以使用如下代码(假设在Xaml中名为myTextBox的TextBox控件):

using System.Windows;
using System.Windows.Controls;

namespace BindingCodeTest
{
    public partial class BindingCode : UserControl
    {
        public string FirstName
        {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FirstName.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FirstNameProperty =
        DependencyProperty.Register("FirstName",
                                     typeof(string),
                                     typeof(BindingCode),
                                     new PropertyMetadata(string.Empty,
                                     new PropertyChangedCallback(OnFirstNameChanged)));

        static void OnFirstNameChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            // Get reference to self
            BindingCode source = (BindingCode)sender;

            // Add Handling Code
            string newValue = (string)args.NewValue;
        }

        public BindingCode()
        {
            InitializeComponent();
            myTextBox.DataContext = this;
            myTextBox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("FirstName"));
            FirstName = "First name";    // Sample change
        }
    }
}

答案 1 :(得分:4)

在Blend 4中,在“数据”标签上>新样本数据..>根据需要命名数据源,例如: 'MySampleDataSource'。然后你的'MySampleDataSource'将有一个'+'按钮(右边的相同数据选项卡),有3个选项。选择“添加简单属性”并将其命名为“FirstName”。然后在TextBox或TextBlock上拖动该属性。

结果如下:

<TextBlock x:Name="firstName" Text="{Binding FirstName}"/>