设置值时WPF文本框绑定不更新

时间:2015-03-16 20:07:51

标签: c# wpf xaml data-binding

我有一个小程序来测试文本框数据绑定,它在我更改文本框本身的值时有效,但是当我尝试从代码隐藏更改值时,变量会更新,但文本框不会更新。我环顾四周但却找不到解决方案,因为我见过的大多数都是文本框更新变量,这与我需要的相反。这是代码:

XAML:

<Grid>
    <TextBox Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="23" Margin="127,37,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox Text="{Binding LastName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="23" Margin="127,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBlock HorizontalAlignment="Left" Margin="28,40,0,0" TextWrapping="Wrap" Text="First Name" VerticalAlignment="Top"/>
    <TextBlock HorizontalAlignment="Left" Margin="28,91,0,0" TextWrapping="Wrap" Text="Last Name" VerticalAlignment="Top"/>
    <Button x:Name="Name" Content="Name!" HorizontalAlignment="Left" Margin="145,212,0,0" VerticalAlignment="Top" Width="75" Click="Name_Click"/>

</Grid>

和我的代码:

namespace WpfApplication1
{
public class UIControls : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _firstName;
    private string _lastName;

    protected void Notify(string propertyName)
    {
        if(this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (value != _firstName)
            {
                _firstName = value;
                Notify("FirstName");
            }

        }
    }
    public string LastName
    {
        get { return _lastName; }
        set
        {
            if (value != _lastName)
            {
                _lastName = value;
                Notify("LastName");
            }
        }
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        UIControls viewModel = new UIControls();
        this.DataContext = viewModel;
    }

    private void Name_Click(object sender, RoutedEventArgs e)
    {
        UIControls ui = new UIControls();
        ui.FirstName = "Mike";
        ui.LastName = "Smith";
    }
}

}

1 个答案:

答案 0 :(得分:1)

您正在每次按下按钮时创建新的UIControl。新的UIControls没有绑定到文本框。尝试创建绑定到MainWindow的私有域,如下所示:

public partial class MainWindow : Window
{

    private UIControls viewModel;
    public MainWindow()
    {
        InitializeComponent();
        viewModel = new UIControls();
        this.DataContext = viewModel;
    }

    private void Name_Click(object sender, RoutedEventArgs e)
    {
        viewModel.FirstName = "Mike";
        viewModel.LastName = "Smith";
    }