我想将一个实体属性(比如Salary)绑定到一个XAML元素的属性(比如 a TextBox.Text),并使用这个绑定来保存Text到TextBox工资字段,该字段作为实体属性绑定到 some 的“文本” TextBox。
类似于以下内容:
<Grid DataContext="Employee">
    <TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
</Grid>
我想将一个实体属性(比如Salary)绑定到一个XAML元素的属性(比如 a TextBox.Text),并使用这个绑定来保存Text到TextBox工资字段,该字段作为实体属性绑定到 some 的“文本” TextBox。
类似于以下内容:
<Grid DataContext="Employee">
    <TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
</Grid>
你可以在 xaml 中绑定属性——所以你的薪水必须是一个属性而不是一个字段。如果您的 Employee 是有薪水的类,您可以将 datacontext 设置为它的一个实例。您可以在 xaml 或代码隐藏或绑定中执行此操作。
public class Employee //implement INotifyPropertyChanged to get the power of binding :)
{
    public decimal Salary {get;set}
}
视图.xaml
<Grid>
 <Grid.DataContext>
        <local:Employee/>
  </Grid.DataContext>
   <TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
 </Grid>
您可以通过多种方式设置数据上下文
在 Visual Studio 2017 中,创建一个 Visual C# 空白应用程序(通用 Windows)。将其命名为“我的项目”。
添加一个类Employee,然后修改样板代码如下:
// Employee.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace MyProject
{
    public class Employee : INotifyPropertyChanged
    {
        private string salary;
        public string Salary
        {
            get
            {
                return this.salary;
            }
            set
            {
                if (value != this.salary)
                {
                    this.salary = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        // This method MUST BE called by the Set accessor of each property for TwoWay binding to work.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        // Constructor with one parameter
        public Employee(string annualSalary) { salary = annualSalary; }
    }
}
请注意,该类Employee实现了INotifyPropertyChanged接口。
将类添加EmployeeViewModel到项目中,并修改样板代码如下:
// EmployeeViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProject
{
    public class EmployeeViewModel
    {
        private Employee defaultEmployee = new Employee("50000");
        public Employee DefaultEmployee { get { return this.defaultEmployee; } }
    }
}
修改MainPage.xaml.cs样板代码如下
//MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace MyProject
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.ViewModel = new EmployeeViewModel();
        }
        public EmployeeViewModel ViewModel { get; set; }
    }
}
修改MainPage.xaml样板代码如下:
<Page
    x:Class="MyProject.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyProject"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <!--TextBlock will provide visual feedback that the two-way binding is working-->
        <TextBlock x:Name="Control" Text="{x:Bind ViewModel.DefaultEmployee.Salary, Mode=OneWay}" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center"/>
        <!--TextBox has two-way binding-->
        <TextBox x:Name="Input" Text="{x:Bind ViewModel.DefaultEmployee.Salary, Mode=TwoWay}" Margin="10" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center"/>
        <!--Button does nothing other than allow TextBox to lose focus-->
        <Button x:Name="btn1" Content="Hello" Grid.Column="1" Grid.Row="3"
          Foreground="Green"
          HorizontalAlignment="Center"/>
    </Grid>
</Page>
注意,'Input'TextBox 和'Control'TextBlock 都绑定Salary到DefaultEmployee. 这个想法是您在'Input'TextBox 中编辑和更改薪水,然后您可以直观地看到双向绑定在工作,因为'Control'TextBlock 会更新。当'Input'TextBox 失去焦点时会发生这种情况(它是为了允许更改焦点,例如在按下 TAB 键后,'Hello'添加了按钮 - 按钮本身绝对什么都不做)。
构建并运行。修改薪水,然后TAB或单击按钮:

不,你不能那样做。您不能将类名称设置为 DataContext。它应该是 Employee 类的实例。