1

我正在尝试使用 WPF 文本框控件为 linq 查询的结果创建双向数据绑定。我编写了一个应用程序来测试这一点,但是虽然我表中的最后一行显示在初始加载中,但是一旦我添加了一个新行,我的文本框中的新值就不会更新。我的代码:

XAML 代码:

<Window x:Class="WpfApplication2Test6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="tbTest" BorderBrush="#FFCB5D5D" Width="50" Height="25" Text="{Binding Source=valueP, Path=ProcessID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        </TextBox>
    </Grid>
</Window>

C#代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.CompilerServices;
using System.ComponentModel;

namespace WpfApplication2Test6
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);  
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            BindingList<ProcessUpdate> processList = new BindingList<ProcessUpdate>();
            var processID = ProcessUpdate.GetNewProcessValue().ProcessID;
            tbTest.Text = processID.ToString();
        }
    }

    public class ProcessUpdate : INotifyPropertyChanged
    {
        private int pid;

        public event PropertyChangedEventHandler PropertyChanged;

         private ProcessUpdate()
        {
            WpfApplication2Test6.MonthlyBudgetEntities entity = new MonthlyBudgetEntities();

            var valueP = (from p in entity.WPFTestTables
                          select new { p.ProcessID }).ToList().Last();

            pid = valueP.ProcessID;

        }

        public static ProcessUpdate GetNewProcessValue()
        {
            return new ProcessUpdate();
        }

        public int ProcessID
        {
            get { return pid; }
            set
            {
                pid = value;
                OnPropertyChanged("ProcessID");
            }
        }

        public void OnPropertyChanged(string pid)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(pid.ToString()));
            }
        }
    }
4

0 回答 0