2

我正在使用表达式混合。

假设我得到了:

Public string FirstName{get;set;}

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

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

4

2 回答 2

6

您实际上希望将属性放在视图模型上,并使用 XAML 绑定,但这是另一回事。

正如您描述您的示例一样,您首先需要将“FirstName”属性实现为依赖属性,而不是简单的获取/设置。这是来自 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
        }
    }
}
于 2010-08-22T18:16:26.133 回答
5

在 Blend 4 中,在“数据”选项卡上 > 新示例数据.. > 根据需要命名数据源,fe 'MySampleDataSource'。然后您的“MySampleDataSource”将有一个“+”按钮(右侧相同的数据选项卡),带有 3 个选项。选择“添加简单属性”并将其命名为“名字”。然后将该属性拖到您的 TextBox 或 TextBlock 上。

结果是这样的:

<TextBlock x:Name="firstName" Text="{Binding FirstName}"/>
于 2010-08-23T14:18:32.640 回答